如何解决在父类组件中使用函数组件 ref
是否可以从类组件 Child
访问函数组件 Parent
的函数和变量?
class Parent extends React.Component{
constructor(props) {
super(props);
this.child = React.createRef();
}
hello = () => {
this.child.current.hello()
}
render(){
return(
<div>
...
<Child ref={this.child} />
<button onClick={this.hello}
</div>
)
}
}
const Child = forwardRef((props,ref) => {
useImperativeHandle(ref,() => ({
hello() {
alert("hello from Child");
}
}));
return <h1>Hi</h1>;
});
解决方法
是的,您的实施应该有效。
你只需要改变你孩子的一件小事
const Child = React.forwardRef((props,ref) => {
const hello = () => {
alert('hello from child')
}
React.useImperativeHandle(ref,() => ({
hello
}))
return <div>hi</div>
})
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。