Javascript React Hooks-如何使用FlatList为renderItem中的每个渲染项指定唯一的“ref”?
我正在尝试将类组件转换为函数组件,并努力将引用分配给平面列表中的每个渲染项 这是原始类组件Javascript React Hooks-如何使用FlatList为renderItem中的每个渲染项指定唯一的“ref”?,javascript,react-native,react-hooks,Javascript,React Native,React Hooks,我正在尝试将类组件转换为函数组件,并努力将引用分配给平面列表中的每个渲染项 这是原始类组件 ... constructor(props) { super(props); this.cellRefs = {}; } .... _renderItem = ({ item }) => { return ( <Item ref={ref => { this.cellRefs[item.id] =
...
constructor(props) {
super(props);
this.cellRefs = {};
}
....
_renderItem = ({ item }) => {
return (
<Item
ref={ref => {
this.cellRefs[item.id] = ref;
}}
{...item}
/>
);
};
...
从医生那里做类似的事情
function TextInputWithFocusButton() {
const inputEl = useRef(null);
const onButtonClick = () => {
// `current` points to the mounted text input element
inputEl.current.focus();
};
return (
<>
<input ref={inputEl} type="text" />
<button onClick={onButtonClick}>Focus the input</button>
</>
);
}
假设您的项和呈现平面列表的组件都需要是功能组件,那么您需要注意两件事 向每个项目组件添加动态参照 确保Item组件使用UseImperialiveHandle和forwardRef来公开函数
注意:如果项目不是功能组件,您可以避免第二步它不会那样工作。ref必须是具有动态属性的对象。
const App = () => {
const cellRefs = useRef({}) // Adding an object as we need more than one ref
const _renderItem = ({ item }) => {
return (
<Item
ref={ref => {
cellRefs.current[item.id] = ref;
}}
{...item}
/>
);
};
....
}
const Item = React.forwardRef((props, ref) => {
...
const handleClick = () => {};
useImperativeHandle(ref, () => ({
// values that need to accessible by component using ref, Ex
handleClick,
}))
...
})