是否可以将 ref 添加到 props.children 元素?

IT技术 javascript reactjs react-redux react-hooks
2021-05-23 19:43:06

我有一个FormInput组件,它们呈现如下。

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

表单组件将在此处充当包装器组件,并且此处未设置字段组件引用。我想通过迭代props.children表格组件和要指派一个ref属性给每个孩子。有没有可能实现这一目标?

2个回答

您需要Form使用React.ChildrenReact.cloneElementAPI注入您的 refs

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

编辑 Vanilla-React-Template(分叉)

您可以使用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, 
         { ...child.props, ref: register(`field-${index}`) }
       )
    }
    </Parent>
 )
}