react hooks使用ref对遍历的组件取值方式
在React Hooks中,我们可以使用`useRef`来获取遍历的组件的值。下面是一个示例:
import React, { useRef, useEffect } from 'react';
reacthooks理解function App() {
  const componentsRef = useRef([]);
  useEffect(() => {
    console.log(componentsRef.current);
  }, []);
  const handleAddComponent = () => {
    componentsRef.current.push('new component');
  };
  return (
    <div>
      <button onClick={handleAddComponent}>Add Component</button>
      <div>
        {componentsRef.current.map((component, index) => (
          <Component key={index} ref={el => componentsRef.current[index] = el} />
        ))}
      </div>
    </div>
  );
}
const Component = React.forwardRef((props, ref) => {
  return <div ref={ref}>Component</div>;
});
export default App;
在这个例子中,我们使用`useRef`创建了一个`componentsRef`引用。然后,在`handleAddComponent`函数中,我们通过操作`componentsRef.current`数组来添加新的遍历组件。
在遍历组件中,我们使用`React.forwardRef`来将`ref`传递给子组件。然后,我们在`ref`属性中将遍历组件的引用指定为`componentsRef.current[index]`。这样,每个遍历组件都会将自己的`ref`对象添加到`componentsRef.current`数组中的相应位置。
最后,在`useEffect`钩子中,我们打印`componentsRef.current`来验证遍历组件的引用。