能否向props.children元素添加ref?

11

我有一个表单输入框组件,它们的呈现方式如下。

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

Form组件将充当包装器组件,这里没有设置Field组件引用。我想在Form组件中遍历props.children并为每个子组件分配ref属性。有可能实现吗?

Form组件作为包装器,Field组件的引用在此未设置。我想通过Form组件遍历props.children并为每个子组件分配ref属性。是否有可能实现这一点?

2个回答

23
你需要使用 Form 来使用 React.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>
  );
};

Edit Vanilla-React-Template (forked)

注意:克隆子组件会使数据流向应用程序变得困难。请尝试其他替代方案之一。


1
我收到了这个警告 index.js:1 警告:函数组件不能被赋予引用。尝试访问此引用将失败。你是不是想使用React.forwardRef()? - itzzmeakhi
在我的例子中,我将 ref 传递给 div,当您将其传递给函数组件时,您需要使用 forwardRef 或使用其他属性,如 innerRef 并传递 ref。 - Dennis Vash
我已经添加了一个示例,你可以直接查找“将引用传递给函数组件”。 - Dennis Vash
1
如果我无法控制子组件怎么办? - DPA
@DPA,您需要更具体一些,请尝试提出一个新问题。 - Dennis Vash
cloneElement 很脆弱,建议使用将组件作为属性进行传递。https://react.dev/reference/react/cloneElement#alternatives - STEEL

6

你可以使用两种方式之一,在其基础上映射子元素并创建组件的新实例,在React文档中展示了这两种方法。

  • 使用React.Children.mapReact.cloneElement(这种方式会保留原元素的 key 和 ref)

  • 或仅使用React.Children.map(只保留原组件的 ref)

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接