React组件onClick处理程序不工作

React component onClick handler not working

本文关键字:工作 程序 处理 组件 onClick React      更新时间:2023-09-26

我有一个基本的弹出窗口(图像),当你点击按钮时会出现。当你在弹出窗口之外点击时,它应该关闭,但当你在里面点击时,应该保持打开状态并调用测试函数。其初始状态isPopupVisible设置为false。当你点击按钮时,我会将状态设置为true,从而呈现弹出窗口。

问题是当你点击图片时,测试函数没有被调用。我认为这是因为状态被设置为false,并且带有onClick函数的图像元素最初没有被渲染。有人知道怎么解决这个问题吗?

(写在ecmascript 6中)

getInitialState () {
  return {isPopupVisible: false}
},
onClick () {
  if(!this.state.isPopupVisible){
    this.setState({isPopupVisible: true});
    document.body.addEventListener('click', this.onClickBody)
  }
},
onClickBody () {
  this.setState({isPopupVisible: false});
  document.body.removeEventListener('click', this.onClickBody)
},
test () {
  console.log('the onClick from the image works!');
},
showPopup () {
  if(this.state.isPopupVisible){
    return <div>
      <img src='img.png' onClick={this.test} />
    </div>
  }else{
    return null;
  }
},
render () {
  return (
    <span>
      <button onClick={this.onClick}>
        See Popup
      </button>
      {this.showPopup()}
    </span>
  );
}

这有点像黑客,但。。。

onClickBody () {
  setTimeout(function(){
    if (!this.clickedInBounds && this.isMounted()) {
      this.setState({isPopupVisible: false});
      document.body.removeEventListener('click', this.onClickBody)
    }
    this.clickedInBounds = false;    
  }.bind(this), 0);
},
test () {
  console.log('the onClick from the image works!');
  this.clickedInBounds = true;
},

setTimeout只是为了让它在test有机会运行之后运行该代码。isMounted只是为了在点击主体和setTimeout之间卸载组件的可能性很小。

jsbin

您可以在呈现弹出窗口之前添加一个底层透明div,而不是在body上添加click侦听器,该弹出窗口将在单击时关闭。

例如,这就是在react bootstrap Modal组件中实现的方式:https://github.com/react-bootstrap/react-bootstrap/blob/master/src/Modal.jsx#L73

您可以在此处查看演示:http://react-bootstrap.github.io/components.html#modals

您的onClickBody处理程序在调用test之前被调用,在触发合成事件之前更改状态并从虚拟DOM中删除映像。

可能有一种优雅的方法可以解决这个问题,但因为您混合了本机和React事件API,我猜您必须更改onClickBody的签名,以将事件作为其第一个参数,然后用类似if (e.target.nodeName !== "IMG") {}的东西包装方法的主体。

JSFiddle在这里展示了这一点:http://jsfiddle.net/reactjs/69z2wepo/

我知道这篇文章已经一年了,但我知道正确的答案。

你有很多参考危险。

onClick () {
  var self = this;
  if(!this.state.isPopupVisible){
    self .setState({isPopupVisible: true});
    document.body.addEventListener('click', self .onClickBody)
  }
},
onClickBody () {
  var self = this;
  this.setState({isPopupVisible: false});
  document.body.removeEventListener('click', self .onClickBody)
},
test () {
  console.log('the onClick from the image works!');
},
showPopup () {
  var self = this;
  if(this.state.isPopupVisible){
    return <div>
      <img src='img.png' onClick={self.test} />
    </div>
  }else{
    return null;
  }
},

这肯定可以解决您的问题