【问题标题】:Hide popup after button press. React Js按下按钮后隐藏弹出窗口。反应JS
【发布时间】:2017-02-06 05:46:29
【问题描述】:

我有一些你喜欢的弹出块或模态窗口。我希望它在我按下按钮后关闭。复选框为真后,按钮将可见。请帮帮我。可能是我必须在 css 中添加一些东西,或者 JS 代码不正确。 代码如下。

class ModalWindow extends React.Component {
  constructor() {
    super();
    this.state = {
      open: false,
      checked: false
    };
    this.handleChange = this.handleChange.bind(this);
  }

  handleChange() {
    this.setState({
      checked: !this.state.checked
    })
  }


  hide() {
    this.setState({
      open: false,
    });
  }

  show() {
    this.setState({
      open: true,
    });


  }

  componentDidMount() {
    this.show();
  }



  render() {
    const buttonContent = this.state.checked ?  <div className={s.showButton}>
      <button onClick={() => this.hide()} className={s.closeBtn}>Confirm yes yes</button>
    </div> : null;
    
    return (
      <div className={this.state.open ? 'show':'hide'}>
        <div className={s.modal}>

          <h2 className={s.modalText}>Some text in block</h2>
          <label>I want to confirm</label>
          <input type="checkbox" checked={this.state.checked} onChange={this.handleChange}/>
          {buttonContent}
        </div>
      </div>
    );
  }
}

export default withStyles(s)(ModalWindow);
.modal {
  background:#fff;
  width: 350px;
  height: 200px;
  margin: 5% auto;
  padding: 5px 20px;
  position: relative;
  border: 2px solid #0000ee;

}

.hide {
display:none
}

.modalText {
  font-size: 18px;
  color: #000000;
}

label {
  margin:0 15px 0 0;
}

.closeBtn {
  display: block;
  position: absolute;
  bottom: 5px;
  width: 150px;
  height:50px;
  margin:0 0 0 100px;
  outline: none;
  color: #555;
  border: none;
  background: #000000;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.14.6/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.14.6/react-dom.min.js"></script>
<div id="container">
    <!-- This element's contents will be replaced with your component. -->
</div>

【问题讨论】:

  • 你有什么问题?看起来代码在那里隐藏它​​,如果没有可运行的演示或更多信息,很难确定到底是什么问题

标签: javascript html css reactjs


【解决方案1】:

使用 react 你有另一种方式来隐藏和显示元素。你只是渲染它,或者你不渲染它。 因此,与其在模态对话框中设置状态来显示或隐藏模态对话框,不如在它之外有一个属性来决定是否呈现此对话框。你的 React 应用应该是这样的:

class ComponentWithModalDialog extends React.Component {
  render() {
    const {showModal} = this.props;


    if(showModal) {
      return <ModalWindow />
    }
    else {
      return <div>
        other content
      </div>
    }
  }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-06-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-04
    相关资源
    最近更新 更多