【问题标题】:How to pass a callback to a child without triggering it如何在不触发的情况下将回调传递给孩子
【发布时间】:2019-04-23 05:37:45
【问题描述】:

我有一个带有模态的 React 应用程序,当单击按钮时会弹出带有游戏规则的窗口。我想要做的是,当我点击这个弹出窗口之外的任何地方时,它会关闭。我有三个文件。 app.js、dialog.js 和 outsidealerter.js。在我的主 app.js 中,当我单击一个按钮时,它会将状态设置为可见,因此我的元素会采用它并基于它进行渲染。我的 outsideralerer.js 基本上可以检测是否在使用特定标签包裹的任何内容之外有点击。现在问题来了,我有一个方法可以更改 app.js 中的可见性状态,所以为了让outsderalerter.js 使用它,我将它传递给它,以便它可以访问我的主要状态并更改它,以便当点击在区域外时,弹出窗口消失。即使我在弹出窗口中单击它也会关闭它,因为当我将值传递给外部警报器时,它会将整个身体视为无点击区域。我的问题是如何防止它触发并只传递一个值,或者是否可以从 outsidealerter.js 更改 app.js 的状态值

App.js

 updateState() {
  this.setState({ isOpen: false });
}

<div id='rule-button'>
<button onClick={(e)=>this.setState({isOpen : true})} id="modalBtn" class="button">Open Rules</button>
</div>

<OutsideAlerter updateParent={ this.updateState.bind(this)}/>

<Dialog isOpen={this.state.isOpen} onClose={(e)=>this.setState({isOpen : false})}>
</Dialog>

outsidealerter.js

handleClickOutside(event) {
    if (this.wrapperRef && !this.wrapperRef.contains(event.target)) {
      //alert('You clicked outside of me!');
     {this.props.updateParent()};
    }
  }

【问题讨论】:

    标签: reactjs


    【解决方案1】:

    我认为让模态框占据窗口高度和宽度的全部空间并使其不可见会更简单,除了您要显示的内容。

    我们可以用onClick={hideModal} 包装模态框,用onClick={e =&gt; e.stopPropagation()} 包装内部内容,这将阻止我们的包装器触发hideModal 处理程序。

    class ModalWrapper extends React.Component {
      state = { isModalOpen: true };
    
      toggleModal = () => {
        this.setState(({ isModalOpen }) => ({
          isModalOpen: !isModalOpen
        }));
      };
    
      render() {
        const { isModalOpen } = this.state;
    
        return (
          <div className="App">
            <button onClick={this.toggleModal}>Open Modal</button>
            {isModalOpen && <Modal hideModal={this.toggleModal} />}
          </div>
        );
      }
    }
    
    function Modal({ hideModal }) {
      return (
        <div onClick={hideModal} className="modal">
          <div onClick={e => e.stopPropagation()} className="modal__content">
            Modal content
          </div>
        </div>
      );
    }
    

    Working example

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-06-04
      • 1970-01-01
      • 2020-02-13
      • 2016-12-18
      • 1970-01-01
      • 2013-06-02
      • 1970-01-01
      • 2020-09-10
      相关资源
      最近更新 更多