我尝试从按钮调用我的Modal组件的show方法。
但这行不通...
class Modal extends React.Component {
constructor(props) {
super(props);
this.show = this.show.bind(this)
}
show(){
console.log('show')
}
render() {
return (
<div>
</div>
);
}
}
class App extends Component {
constructor(props) {
super(props);
this.modalRef= React.createRef();
}
render() {
return (
<div>
<Modal ref={this.modalRef}/>
<button id="myBtn" onClick={this.modalRef.show}>call show modal method</button>
</div>
);
}
}
我使用ref从链接访问Modal组件。
任何的想法 ?
通常,您可以通过传递一个prop来实现,而不是直接在组件上调用方法: