【问题标题】:opening a modal with the click of a button单击按钮打开模式
【发布时间】:2017-12-12 05:44:57
【问题描述】:

接下来的代码使用了一个 Modal react 组件:

export class AddWorkLogEditor extends React.Component {
    constructor(props) {
        super(props);

        this.addWorkLog = this.addWorkLog.bind(this);       
        this.onOpenModal = this.onOpenModal.bind(this);
        this.onCloseModal = this.onCloseModal.bind(this);
        this.state = {
             open:true

           };
      }

  onOpenModal() {
     this.setState({open: this.props.openModal});
  }

  onCloseModal() {
     this.setState({open:false});
  }

  addWorkLog() {

   }



 render() {
      const bstyle = {
         backgroundColor: 'green',
         textAlign:"left",
         paddingLeft: '0px',
         color: 'white'
    };
 const {open} = this.state;
       return (
           <div>
                <Modal open={open} onClose={this.onCloseModal} little>
                <h3>hi gi</h3>

                 <Button bsStyle="success" bsSize="small" onClick ={(ev) => {console.log(ev)} }> Save </Button>
                 </Modal>
            </div>
       );
    }
}

我正在尝试使用:

addWorkLog()
{
      return <AddWorkLogEditor/>;
}

 createAddWorkLogButton () {

    return (
        <button style={ { color: '#007a86'} } onClick={this.addWorkLog} >Add Work Log</button>
    );
 }

我的意思是,单击此按钮后,什么都没有显示。还有另一种方式来调用该模态吗?我正在从以下位置导入模态:

从“react-responsive-modal”导入模态

【问题讨论】:

    标签: reactjs ecmascript-6 modal-dialog jsx


    【解决方案1】:

    您试图仅在单击按钮后才呈现模式,虽然这对于非反应环境来说是很自然的,但在反应中它以不同的方式工作。在最简单的解决方案中,应始终呈现Modal,当用户单击按钮时,您将模态open 属性更改为true

    { /* all the markup of your page */ }
    <button onClick={() => this.setState({showModal: true})}>Add Work Log</button>
    { /* anything else */ }
    
    { /* modal is here but it is hidden */ }
    <Modal open={this.state.showModal}>...</Modal>
    

    或者,您可以完全跳过模态渲染,直到 showModal 变为 true。

    this.state.showModal && <Modal open>...</Modal>
    

    【讨论】:

    • 我想我明白你的意思了……让我试试吧!非常感谢!
    • 如果Modal 已关闭,如何将 showModal 的状态再次更改回 false?我曾尝试使用模态 onClose,但即使单击确认按钮也会调用它
    猜你喜欢
    • 2018-10-29
    • 2015-07-07
    • 2023-03-14
    • 2018-07-05
    • 1970-01-01
    • 2015-03-08
    • 1970-01-01
    • 1970-01-01
    • 2018-10-05
    相关资源
    最近更新 更多