单击按钮以在ReactJS中打开对话框

时间:2018-09-12 10:22:59

标签: reactjs dialog frontend react-modal

我正在使用React MDL库,并且使用了 FABButton

之类的预定义组件
<FABButton>
  <Icon name="add"/>
</FABButton>  

它如下图所示显示按钮:
enter image description here

现在,我要显示的是带有+图标的对话框...而不是这里发生的情况:

enter image description here

这是在以下代码之后发生的:

<FABButton>
  <AddingProject />
  <Icon name="add" />
</FABButton>

对话框的类别如下:

class AddingProject extends Component {
  constructor(props) {
    super(props);
    this.state = {};
    this.handleOpenDialog = this.handleOpenDialog.bind(this);
    this.handleCloseDialog = this.handleCloseDialog.bind(this);
  }
  handleOpenDialog() {
    this.setState({
      openDialog: true
    });
  }

  handleCloseDialog() {
    this.setState({
      openDialog: false
    });
  }
  render() {
    return (
      <div>
        <Button colored onClick={this.handleOpenDialog} raised ripple>
          Show Dialog
        </Button>
        <Dialog open={this.state.openDialog} onCancel={this.handleCloseDialog}>
          <DialogTitle>Allow data collection?</DialogTitle>
          <DialogContent>
            <p>
              Allowing us to collect data will let us get you the information
              you want faster.
            </p>
          </DialogContent>
          <DialogActions>
            <Button type="button">Agree</Button>
            <Button type="button" onClick={this.handleCloseDialog}>
              Disagree
            </Button>
          </DialogActions>
        </Dialog>
      </div>
    );
  }
}

export default AddingProject;

上面的代码带有必需的 import 语句

1 个答案:

答案 0 :(得分:1)

这对我有用....
第一步:我添加了模态组件,如下所示:

<FABButton>
  <Icon name="add" />
</FABButton>
<ProjectModal>

第二步:我为组件添加了此道具:visible,如下所示:

<ProjectModal visible={this.state.showDialog} />

在这里,您需要使用showDialogfalse添加到类中的状态。

state = {
  showDialog: false
};

现在,进入第3步。
第三步:将这一部分添加到您的代码中,以在您单击时调用。

openModal = () => {
  this.setState({ showDialog: true });
};

另一方面,您需要在按钮中实现onClick,如下所示:

<FABButton onClick={this.openModal.bind(this)}>
  <Icon name="add" />
</FABButton>

第四步::在模态/对话框类中,您需要将可见对象存储在新的状态变量中,该变量位于showDialogModal

constructor(props, context) {
super(props, context);
this.state = {
    showDialogModal: this.props.visible
  };
}

现在,您需要将更改后的状态从第一类传递给modal / dialog类,React提供了多个选项,我在第五步中使用了这个选项。 第五步:如下使用此React事件componentWillReceiveProps

componentWillReceiveProps(nextProps) {
if (this.props.showDialogModal != nextProps.visible) {
  this.setState({
    showDialogModal: nextProps.visible
   });
  }
}

这将反映visible属性从第一类到此处的新类showDialogModal的任何变化
现在在渲染部分,您需要检查组件的文档,这里我从React-Bootstrap开始。 第六步:使用组件中的show属性。

<Modal show={this.state.showDialogModal} onHide={this.closeModal}>

onHide用于关闭对话框,这也使您也需要实现。

closeModal = () => {
  this.setState({ showDialogModal: false });
};

最后,在关闭按钮中,添加以下内容:

<Button onClick={this.closeModal.bind(this)}>Close</Button>

祝你好运。