无法在react中分配新属性,得到“无法添加属性xxx,对象不可扩展”

时间:2017-09-05 09:43:06

标签: javascript reactjs ecmascript-6

我想制作一个用于提交表单的对话框组件。

代码

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>
    )
  }

};

目的

我想传递

  1. 带有handleSumbit函数(子项)的表单
  2. 一个可点击的元素,用于打开此对话框(触发器)
  3. 因为外部组件不知道如何打开此对话框,所以我倾向于将元素传递给对话框,并让对话框将onClick函数传递给它。 但是我发现我无法将set属性添加到this.props.trigger。我尝试添加React.cloneElement,但仍无效。

    尝试Object.sealenter image description here

1 个答案:

答案 0 :(得分:3)

尝试:

React.cloneElement(this.props.trigger, {
        onClick: this.toggleDialog
});