我有一个表单和输入框组件,它们的呈现方式如下。
<Form>
<Field />
<Field />
<Field />
</Form>
Form组件将充当包装器组件,这里没有设置Field组件引用。我想在Form组件中遍历props.children并为每个子组件分配ref属性。有可能实现吗?
Form组件作为包装器,Field组件的引用在此未设置。我想通过Form组件遍历props.children并为每个子组件分配ref属性。是否有可能实现这一点?
我有一个表单和输入框组件,它们的呈现方式如下。
<Form>
<Field />
<Field />
<Field />
</Form>
Form组件将充当包装器组件,这里没有设置Field组件引用。我想在Form组件中遍历props.children并为每个子组件分配ref属性。有可能实现吗?
Form组件作为包装器,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文档中展示了这两种方法。
使用React.Children.map
和React.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>
)
}
div
,当您将其传递给函数组件时,您需要使用forwardRef
或使用其他属性,如innerRef
并传递 ref。 - Dennis VashcloneElement
很脆弱,建议使用将组件作为属性进行传递。https://react.dev/reference/react/cloneElement#alternatives - STEEL