How can I access a hover state in reactjs?

前端 未结 4 746
清酒与你
清酒与你 2021-01-30 04:40

I have a sidenav with a bunch of basketball teams. So I would like to display something different for each team when one of them is being hovered over. Also, I am using Reactjs

4条回答
  •  不知归路
    2021-01-30 05:34

    I know the accepted answer is great but for anyone who is looking for a hover like feel you can use setTimeout on mouseover and save the handle in a map (of let's say list ids to setTimeout Handle). On mouseover clear the handle from setTimeout and delete it from the map

    onMouseOver={() => this.onMouseOver(someId)}
    onMouseOut={() => this.onMouseOut(someId)
    

    And implement the map as follows:

    onMouseOver(listId: string) {
      this.setState({
        ... // whatever
      });
    
      const handle = setTimeout(() => {
        scrollPreviewToComponentId(listId);
      }, 1000); // Replace 1000ms with any time you feel is good enough for your hover action
      this.hoverHandleMap[listId] = handle;
    }
    
    onMouseOut(listId: string) {
      this.setState({
        ... // whatever
      });
    
      const handle = this.hoverHandleMap[listId];
      clearTimeout(handle);
      delete this.hoverHandleMap[listId];
    }
    

    And the map is like so,

    hoverHandleMap: { [listId: string]: NodeJS.Timeout } = {};
    

    I prefer onMouseOver and onMouseOut because it also applies to all the children in the HTMLElement. If this is not required you may use onMouseEnter and onMouseLeave respectively.

提交回复
热议问题