如何解决使用自定义引用创建组件并稍后访问它
我想使用自定义 Refs 动态创建组件,并且我想使用这些 refs 并使用 measure() 等功能。
我创建了以下代码
var elems = [];
const CarousalLoop = (props) => {
var links = [
{ name: 'america' },{ name: 'canada' },{ name: 'norway' },{ name: 'bahamas' }
];
links.forEach((val,index) => {
elems[val.name]= useRef(null);
});
const listItems = links.map((link) =>
<CustomCarousel ref={elems[link.name]} category={link.name}/>
);
return (
<View style={{backgroundColor:"white"}}>
{listItems}
</View>
);
}
例如,我想使用 elems["america"] 访问组件并稍后使用它。 但我收到以下错误。
Warning: Function components cannot be given refs. Attempts to access this ref will fail. Did you mean to use React.forwardRef()?
解决方法
问题
- 是的,使用函数式组件时需要转发 React refs。
- 您不能在循环中使用
useRef
钩子。
解决方案
修复创建参考。使用 React ref 保存创建的 ref 数组,并通过映射索引传递它们。
const CarousalLoop = (props) => {
const linkRefs = useRef([]);
const links = [
{ name: 'america' },{ name: 'canada' },{ name: 'norway' },{ name: 'bahamas' }
];
linkRefs.current = links.map((link) => linkRefs.current[link.name] ?? createRef());
const listItems = links.map((link) => (
<CustomCarousel
key={link.name}
ref={linkRefs.current[link.name]}
category={link.name}
/>
));
return (
<View style={{backgroundColor:"white"}}>
{listItems}
</View>
);
}
转发参考。这是通过将 CustomCarousel
包装在 React.forwardRef
中来完成的。
const CustomCarousel = React.forwardRef((props,ref) => {
// component logic
// attach `ref` to DOMNode if necessary or access in `useImperativeHandle` hook
...
});
稍后当您想要/需要访问特定引用时,通过 is key 引用它,然后访问当前值。
linkRefs.current['america']?.current
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。