我想制作一个用于提交表单的对话框组件。
代码
class SubmitDialog extends React.PureComponent {
toggleDialog() {
this.setState({isOpen:!this.state.isOpen})
}
handleSubmit() {
// children need have handleSubmit
this.props.children.props.handleSubmit()
this.toggleDialog()
}
render(){
const {children, title } = this.props;
// I want to pass a button to trigger open this dialog
let trigger = React.cloneElement(this.props.trigger);
trigger.onClick = this.toggleDialog;
return (
{trigger},
<Dialog
open={this.state.isOpen}
onClose={() => {this.toggleDialog()}}
className="dialog"
>
<DialogHeader>
<DialogTitle>{title}</DialogTitle>
</DialogHeader>
<DialogBody scrollable className="dialog-body">
{children}
</DialogBody>
<DialogFooter className="align-axis">
<Button raised className="cyan white-text" onClick={()=> { this.toggleDialog() }}>取消</Button>
<Button raised primary onClick={()=> { this.handleSubmit() }} >提交</Button>
</DialogFooter>
</Dialog>
)
}
};
目的
我想通过
- 带有handleSumbit函数的表单(子级)
- 用于打开此对话框的可点击元素(触发器)
因为外部组件不知道如何打开这个对话框,所以我倾向于将元素传递到对话框中,并让对话框传递一个 onClick 函数给它。
但我发现我无法将 set 属性添加到 this.props.trigger
。我尝试添加 React.cloneElement
,但仍然不起作用。
最佳答案
尝试:
React.cloneElement(this.props.trigger, {
onClick: this.toggleDialog
});
关于javascript - 无法在react中分配新属性,得到 ` Can' t添加属性xxx,对象不可扩展`,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46051830/