【问题标题】:React-Hooks- How to assign an unique "ref" to every rendered item in a renderItem using FlatList?React-Hooks-如何使用 FlatList 为 renderItem 中的每个渲染项分配一个唯一的“ref”?
【发布时间】:2020-05-17 11:47:48
【问题描述】:

我正在尝试将类组件转换为函数组件,并努力将 refs 分配给 Flatlist 中的每个呈现项目。

这是原来的类组件。



... 

constructor(props) {
    super(props);
    this.cellRefs = {};
  }

....


_renderItem = ({ item }) => {
    return (
      <Item
        ref={ref => {
          this.cellRefs[item.id] = ref;
        }}
        {...item}
      />
    );
  };

...

【问题讨论】:

    标签: javascript react-native react-hooks


    【解决方案1】:

    假设你的 Item 和渲染 FlatList 的组件都需要是功能组件,你需要处理两件事

    • 为每个 Item 组件添加动态引用
    • 确保 Item 组件使用 useImperativeHandle 和 forwardRef 来公开函数
    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}
          />
        );
      };
      ....
    }
    
    

    发布您需要更改您的 Item 组件,例如

    const Item = React.forwardRef((props, ref) => {
       ...
       const handleClick = () => {};
       useImperativeHandle(ref, () => ({
            // values that need to accessible by component using ref, Ex
            handleClick,
    
       }))
       ...
    })
    

    P.S.如果Item不是函数式组件,可以省略第二步

    【讨论】:

      【解决方案2】:

      做类似的事情(来自 react doc)

         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>
          </>
        );
      }
      

      【讨论】:

      • 这样不行。 ref 必须是具有动态属性的对象。
      猜你喜欢
      • 2019-01-27
      • 1970-01-01
      • 1970-01-01
      • 2018-06-26
      • 1970-01-01
      • 2019-04-06
      • 2012-09-04
      • 1970-01-01
      • 2020-12-05
      相关资源
      最近更新 更多