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

itz*_*khi 5 javascript reactjs react-redux react-hooks

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

<Form>
   <Field />
   <Field />
   <Field />
</Form>
Run Code Online (Sandbox Code Playgroud)

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

Den*_*ash 6

您需要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>
  );
};
Run Code Online (Sandbox Code Playgroud)

编辑 Vanilla-React-Template(分叉)


Bru*_*oso 6

您可以使用React Docs中显示的两种方法之一来映射子级基于它创建组件的新实例。

  • 使用React.Children.mapand React.cloneElement(这样,原始元素的 key 和 ref 被保留)

  • 或者仅使用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>
 )
}
Run Code Online (Sandbox Code Playgroud)