简体   繁体   English

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

[英]Is it possible to add ref to the props.children elements?

I have a Form and Input components, which are rendered as below.我有一个FormInput组件,它们呈现如下。

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

Form component will act as wrapper component here and Field component ref are not being set here. Form组件将在此处充当包装器组件,而Field组件 ref 未在此处设置。 I want iterate through props.children in Form Component and want to assign a ref attribute to each children.我想遍历Form Component 中的props.children并想为每个孩子分配一个 ref 属性。 Is there any possibility to achieve this?有没有可能实现这一目标?

You need Form to inject your refs with React.Children and React.cloneElement APIs:您需要FormReact.ChildrenReact.cloneElement API 注入您的 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(分叉)

You can map children create new instance of component based on it using one of two ways showed in React Docs .您可以 map children 使用React Docs中显示的两种方法之一基于它创建组件的新实例。

  • With React.Children.map and React.cloneElement (this way, key and ref from original element are preserved)使用React.Children.mapReact.cloneElement (这样,原始元素的 key 和 ref 被保留)

  • Or only with React.Children.map (Only ref from original component is preserved)或者仅使用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>
 )
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM