将回调函数作为 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>
}
}
关于javascript - 如何调用子组件的实例方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56818348/