是否可以将 ref 添加到 props.children 元素? [英] Is it possible to add ref to the props.children elements?
本文介绍了是否可以将 ref 添加到 props.children 元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个 Form 和 Input 组件,它们呈现如下.
I have a Form and Input components, which are rendered as below.
<Form>
<Field />
<Field />
<Field />
</Form>
Form 组件将在此处充当包装器组件,并且 Field 组件引用不在此处设置.我想在 Form 组件中遍历 props.children 并希望为每个孩子分配一个 ref 属性.有没有可能做到这一点?
Form component will act as wrapper component here and Field component ref are not being set here. I want iterate through props.children in Form Component and want to assign a ref attribute to each children. Is there any possibility to achieve this?
推荐答案
你需要 Form
用 React.Children
和 React.cloneElement<注入你的引用/code> API:
You need Form
to inject your refs with React.Children
and React.cloneElement
APIs:
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>
);
};
这篇关于是否可以将 ref 添加到 props.children 元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文