我有一个 Form 和 Input 组件,其呈现如下。
<Form>
<Field />
<Field />
<Field />
</Form>
表单组件将在此处充当包装器组件,而此处未设置 Field 组件引用。我想遍历 Form 组件中的 props.children ,并希望为每个孩子分配一个ref属性。有可能实现这一目标吗?
答案 0 :(得分:2)
您需要Form
来使用React.Children
和React.cloneElement
API注入引用:
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>
);
};
答案 1 :(得分:1)
您可以使用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,
{ref: register(`field-${index}`, ...child.props
)
}
</Parent>
)
}