是否可以在props.children元素中添加ref?

时间:2020-08-30 06:07:55

标签: javascript reactjs react-redux react-hooks

我有一个 Form Input 组件,其呈现如下。

<Form>
   <Field />
   <Field />
   <Field />
</Form>

表单组件将在此处充当包装器组件,而此处未设置 Field 组件引用。我想遍历 Form 组件中的 props.children ,并希望为每个孩子分配一个ref属性。有可能实现这一目标吗?

2 个答案:

答案 0 :(得分:2)

您需要Form来使用React.ChildrenReact.cloneElement API注入引用:

const FunctionComponentForward = React.forwardRef((props, ref) => (
  <div ref={ref}>Function Component Forward</div>
));

const Form = ({ children }) => {
  const childrenRef = useRef([]);

  useEffect(() => {
    console.log("Form Children", childrenRef.current);
  }, []);

  return (
    <>
      {React.Children.map(children, (child, index) =>
        React.cloneElement(child, {
          ref: (ref) => (childrenRef.current[index] = ref)
        })
      )}
    </>
  );
};

const App = () => {
  return (
    <Form>
      <div>Hello</div>
      <FunctionComponentForward />
    </Form>
  );
};

Edit Vanilla-React-Template (forked)

答案 1 :(得分:1)

您可以使用React Docs中显示的两种方式之一,映射子项以基于该子项创建新的组件实例。

  • 使用React.Children.mapReact.cloneElement(这样可以保留原始元素的键和引用)

  • 或仅与React.Children.map(仅保留原始组件的引用)

function useRefs() {
  const refs = useRef({});

  const register = useCallback((refName) => ref => {
    refs.current[refName] = ref;
  }, []);

  return [refs, register];
}

function WithoutCloneComponent({children, ...props}) {

 const [refs, register] = useRefs(); 

 return (
    <Parent>
     {React.Children.map((Child, index) => (
       <Child.type 
         {...Child.props}
         ref={register(`${field-${index}}`)}
         />
    )}
    </Parent>
 )
}

function WithCloneComponent({children, ...props}) {

 const [refs, register] = useRefs(); 

 return (
    <Parent>
     {
       React.Children.map((child, index) => React.cloneElement(
         child, 
         {ref: register(`field-${index}`, ...child.props
       )
    }
    </Parent>
 )
}
相关问题