gpt4 book ai didi

javascript - 如何调用子组件的实例方法?

转载 作者:行者123 更新时间:2023-11-29 10:56:09 25 4
gpt4 key购买 nike

将回调函数作为 props 传递给子组件很简单,但反之则不然。

我们如何调用子组件的实例方法?

来自 <Parent />组件,我需要调用 this.bar <Child /> 的实例方法成分。

class Parent extends React.Component {
render() {
return (
<Child />
)
}
}

class Child extends React.Component {
constructor( props ) {
super( props );
this.bar = () => console.log('foo');

}

}

最佳答案

您可以使用 refs 来做到这一点。

class Parent extends React.Component {
constructor(props) {
super(props);
this.childRef = React.createRef();
}

componentDidMount() {
this.childRef.current.bar()
}

render() {
return (
<Child ref={this.childRef} />
);
}
}

class Child extends React.Component {
constructor( props ) {
super( props );
this.bar = () => console.log('foo');
}

render() {
return <p>Child</p>
}
}

查看 Refs documentation

关于javascript - 如何调用子组件的实例方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56818348/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com