简体   繁体   English

如何在鼠标事件 React JS 上杀死组件状态

[英]How to kill a component state on a mouse event React JS

I have a popup that turns on/off when I hover over/leave a button, currently it's set to false in my props, I would like to set it to true so when the load pages you see the pop up but when the use hovers over it, the state resets back to false so I can hover over it again and see it, but I can't seem to figure it out.我有一个弹出窗口,当我将鼠标悬停在/离开按钮上时会打开/关闭,目前它在我的道具中设置为 false,我想将其设置为 true,以便在加载页面时您看到弹出窗口但当使用悬停时在它上面,状态会重置回 false,这样我就可以再次将鼠标悬停在它上面并查看它,但我似乎无法弄清楚。

class App extends Component {

 constructor(props) {
    super(props);

   this.state = { isHovered: false };
   this.handleHover = this.handleHover.bind(this);
 
 }

 handleHover(){
    this.setState({
        isHovered: !this.state.isHovered
    });
 }

 render() {

    const box = this.state.isHovered ? "box open" : "box";

    return(

       <a className="spot1" 
          onMouseEnter={this.handleHover} 
          onMouseLeave={this.handleHover}>
      </a>

      <div className={box}>
         <p>Lorem ipsum dolor si</p>
      </div>

    )
}

I believe you need a second variable to check if your component was loaded/rendered for first time, Below you can find a simple example.我相信您需要第二个变量来检查您的组件是否是第一次加载/渲染,您可以在下面找到一个简单的示例。

class Item extends React.Component {
  constructor(props) {
    super(props);
    this.state = {loaded : true, hovered : false};

  }

  popState () {
    const {loaded, hovered} = this.state; 
    // check if the component was loaded
    // which will be only once
    // because the state for loaded will be set to false
    if (loaded) {
        return this.setState({
          hovered : !hovered,
          loaded : false
        });
    }
    this.setState({
      hovered : !hovered
    });
  }

  render () {
    const {loaded, hovered} = this.state;
    let box;
    // first page reload
    if (loaded) {
      box = 'show';
    } else {
      box = hovered ? 'show' : 'hide';
    }

    return (
      <a 
        onMouseEnter={this.popState.bind(this)} 
        onMouseLeave={this.popState.bind(this)}>
        My link
        <div 
          className={box}>Tooltip</div>
      </a>
     );
  }
}

You have the making of what you want, it's not hooked up correctly yet.您可以制作您想要的东西,但尚未正确连接。

First, set your isHovered: true so that the popup appears on page load.首先,设置您的isHovered: true以便在页面加载时显示弹出窗口。

Next, change the function onMouseEnter and onMouseLeave to this.handleHover , that's all you should need to do.接下来,将函数onMouseEnteronMouseLeavethis.handleHover ,这就是您需要做的全部事情。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM