简体   繁体   English

反应组件状态不起作用

[英]React Component State not working

I have been trying to implement a hover effect on a div-element like in this codesandbox: https://codesandbox.io/s/XopkqJ5oV 我一直在尝试在div元素上实现悬停效果,例如以下codeandbox: https ://codesandbox.io/s/XopkqJ5oV

The component in which I want to do this, is a reusable component that is used multiple times on the same page. 我要在其中执行此操作的组件是可重复使用的组件,该组件在同一页面上多次使用。 I suppose that is the reason why I can't get it to work. 我想这就是为什么我无法使它工作的原因。 What am I missing? 我想念什么?

Even using the above code won't work in my application. 即使使用上面的代码在我的应用程序中也不起作用。


EDIT : Thank you for your responses. 编辑 :谢谢您的答复。 I found the issue: 我发现了问题:

I was not letting ShouldComponentUpdate know, it should take state.isHovering into account. 我没有让ShouldComponentUpdate知道,它应该考虑state.isHovering。

 shouldComponentUpdate(nextProps, nextState) {
    return (
      nextProps.post.id !== this.props.post.id ||
      nextProps.screenshotClickUrl !== this.props.screenshotClickUrl ||
      nextProps.onImageClick !== this.props.onImageClick ||
      nextProps.handleMouseHover !== this.props.handleMouseHover ||
      nextState.isHovering !== this.state.isHovering
    )
  }

You're missing a this in: 您在以下位置缺少this

  toggleHoverState(state) {
    return {
      isHovering: !state.isHovering // Need a "this" to access state.
    };
  }

If you stack the elements too closely it will interfere with the mouse enter/leave events, eg, if you space them apart: 如果将元素堆叠得太紧密,将干扰鼠标的进入/离开事件,例如,如果将它们隔开,则:

const Foo = () => {
  return (
    <div>
      <HoverExample />
      <div style={{height: '2em', border: '1px solid blue'}} />
      <HoverExample />
    </div>
  )
}

it work like (I think) you'd expect. 它像您期望的那样工作(我认为)。

https://codesandbox.io/s/93l25m453o https://codesandbox.io/s/93l25m453o

I put borders around it to help visualize the issue. 我在其周围放置边框以帮助可视化该问题。

If that doesn't make sense, see what happens when you have the hover indicator in an adjacent span rather than stacked: 如果那没有意义,请查看将鼠标指针放在相邻跨度中而不是堆叠时会发生什么:

https://codesandbox.io/s/5k5jj3rpok https://codesandbox.io/s/5k5jj3rpok

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

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