我有一个Form和Input组件,它们呈现如下。
<Form>
<Field />
<Field />
<Field />
</Form>
表单组件将在此处充当包装器组件,并且此处未设置字段组件引用。我想通过迭代props.children在表格组件和要指派一个ref属性给每个孩子。有没有可能实现这一目标?
我有一个Form和Input组件,它们呈现如下。
<Form>
<Field />
<Field />
<Field />
</Form>
表单组件将在此处充当包装器组件,并且此处未设置字段组件引用。我想通过迭代props.children在表格组件和要指派一个ref属性给每个孩子。有没有可能实现这一目标?
您需要Form
使用React.Children
和React.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>
);
};
您可以使用React Docs 中显示的两种方式之一映射子项,基于它创建组件的新实例。
使用React.Children.map
和React.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>
)
}