【问题标题】:Create components with custom refs and access it later使用自定义 refs 创建组件并稍后访问它
【发布时间】:2021-06-15 19:01:46
【问题描述】:

我想使用自定义 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()?

【问题讨论】:

    标签: reactjs react-native react-hooks react-ref


    【解决方案1】:

    问题

    1. 是的,使用功能组件时需要转发 React refs。
    2. 您不能在循环中使用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
      ...
    });
    

    稍后当您想要/需要访问特定 ref 时,通过 is key 引用它,然后访问当前值。

    linkRefs.current['america']?.current
    

    【讨论】:

    • 这是否有自定义名称 refs ?我看到我们只是将索引传递给 refs。
    • 你还能再举一些例子,什么应该在 CustomCarousel 里面?我使用 rect native。
    • @Graciewilliams 对不起,我不明白你的问题。关于CustomCarousel,这不是你的组件吗?您是在问将引用附加到什么或如何在 CustomCarousel 组件中访问它?
    • 现在我在我的主应用程序中使用 并且它工作正常,我想稍后通过 linkRefs["america"] 访问它,你能举个例子吗。
    • 谢谢,我刚刚使用了 refs 来查看,它解决了这个问题。
    猜你喜欢
    • 2011-03-31
    • 1970-01-01
    • 2021-07-11
    • 2016-08-11
    • 1970-01-01
    • 1970-01-01
    • 2015-12-21
    • 1970-01-01
    • 2014-12-15
    相关资源
    最近更新 更多