【发布时间】:2019-11-27 00:55:56
【问题描述】:
我正在尝试从父组件中的按钮单击事件调用子组件中的函数。
父组件:
class Parent extends Component{
constructor(props){
super(props);
this.state = {
//..
}
}
handleSaveDialog = (handleSaveClick) => {
this.handleSaveClick = handleSaveClick;
}
render(){
return(
<div>
<Button onClick={this.openDialog}>Open Dialog</Button>
<Dialog>
<DialogTitle id="form-dialog-title">Child Dialog</DialogTitle>
<DialogContent>
<Child handleSaveData={this.handleSaveDialog}/>
</DialogContent>
<DialogActions>
<Button onClick={this.handleSaveClick} color="primary">
Save
</Button>
</DialogActions>
</Dialog>
</div>
);
}
}
在上面的代码中,父组件在单击按钮时呈现一个子组件模式对话框(基于 Material-UI)。保存按钮是 Parent 中 Dialog 组件的一部分,单击时应调用 Child 组件中的保存函数。如您所见,我通过名为handleSaveData 的Childcomponent 属性传递了一个回调函数handleSaveDialog。一旦子组件挂载并将回调传递给父组件,保存按钮单击将在子组件上调用handleSaveClick。
子组件:
class Child extends Component{
constructor(props){
super(props);
this.state = {
//..
}
}
componentDidMount(){
console.log('mount');
this.props.handleSaveData( () => this.handleSaveClick());
}
handleSaveClick = () => {
console.log('save clicked');
}
render(){
return(
<div>
//..
</div>
);
}
}
在上面的代码中,我使用的是访问Parent组件props传递的回调函数并将其绑定到Child组件的保存函数handleSaveClick。
问题:
当我在 Parent 中单击 Open Dialog 按钮时,Dialog 第一次安装了 Child 组件。但是,单击Save 按钮不起作用(没有错误)。之后,关闭对话框,当我重新打开对话框并单击保存时,将触发子对话框中的 handleSaveClick,并在浏览器控制台中记录一条消息。知道为什么这在第二次而不是第一次有效吗?
请记住,只有当我单击父组件上的打开对话框时,子组件才会被安装/加载。
参考资料:
https://material-ui.com/components/dialogs/#form-dialogs
https://github.com/kriasoft/react-starter-kit/issues/909#issuecomment-390556015
【问题讨论】:
-
你能把你的代码放在codesandbox或stackblitz之类的地方吗?从这里很难说。
标签: javascript reactjs material-ui