从父级调用子方法我有两个组成部分。父组件子组件我试图从父母那里调用孩子的方法,我试过这样做,但没有得到结果class Parent extends Component {
render() {
return (
<Child>
<button onClick={Child.getAlert()}>Click</button>
</Child>
);
}
}class Child extends Component {
getAlert() {
alert('clicked');
}
render() {
return (
<h1 ref="hello">Hello</h1>
);
}}有办法从父级调用子方法吗?注意:子组件和父组件位于两个不同的文件中。
3 回答
慕慕森
TA贡献1856条经验 获得超17个赞
class Parent extends Component {
render() {
return (
<div>
<Child setClick={click => this.clickChild = click}/>
<button onClick={() => this.clickChild()}>Click</button>
</div>
);
}}class Child extends Component {
constructor(props) {
super(props);
this.getAlert = this.getAlert.bind(this);
}
componentDidMount() {
this.props.setClick(this.getAlert);
}
getAlert() {
alert('clicked');
}
render() {
return (
<h1 ref="hello">Hello</h1>
);
}}clickChildclickChildgetAlert.
connect()getWrappedInstance()
onClick={this.clickChild}this.clickChildonClick={() => this.clickChild()}this.clickChild
添加回答
举报
0/150
提交
取消
