我需要在父组件中调用子组件的函数。我该怎么做呢?之前在 React 15 中,我可以使用 refs 来调用子函数。但不知道如何使用钩子和功能组件来做到这一点。
function Child(props) {
function validate() {
// to validate this component
}
return (
<>Some code here</>
)
}
function Parent(props) {
const refs = useRef([]);
const someData = [1,2,3,4,5];
function validateChildren() {
refs.current.forEach(child => {
child.current.validate(); // throw error!! can not get validate function
});
}
return (
<>
<button onClick={validateChildren}>Validate</button>
{
someData.map((data, index) => {
return <Child ref={ins => refs.current[index] = ins} />
})
}
</>
)
}
我的实际要求是:
1.有多个选项卡,可以根据用户的行为添加、删除
2. 单击选项卡父级中的按钮触发验证
3. 所有选项卡都需要验证自身,在选项卡中显示错误消息并返回验证消息
您可以使用useImperativeHandle
with forwardRef https://reactjs.org/docs/forwarding-refs.html.
来自docs https://reactjs.org/docs/hooks-reference.html#useimperativehandle,
使用命令句柄自定义使用 ref 时暴露给父组件的实例值。与往常一样,在大多数情况下应避免使用引用的命令式代码。使用命令句柄应该与使用前向引用
const Child = React.forwardRef((props,ref) => {
//validate will be available to parent component using ref
useImperativeHandle(ref, () => ({
validate() {
// to validate this component
console.log("I'm clicked");
}
}));
return (
<>Some code here</>
)
})
在父组件中,您可以访问子函数,如下所示:
function validateChildren() {
refs.current.forEach(child => {
child.validate(); // you can access child method here
});
}
Demo https://stackblitz.com/edit/react-a1mlqw
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)