You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

react-waypoint组件onEnter/onLeave回调无法正确更新状态求助

Fix for react-waypoint onLeave Not Updating State to Hide Div

Looks like you've got a simple typo in your onLeave method that's causing the issue! Let's break it down:

The Problem

In your onLeave callback, you're checking this.currentPosition === Waypoint.below, but this.currentPosition doesn't exist on your component instance. You should be using the currentPosition parameter that's passed into the callback instead. That's why your state never updates when the waypoint leaves the viewport.

Fixed Code

class WhenInView extends Component { 
  constructor(props){ 
    super(props); 
    this.state = { isInView: false }; 
    this.onEnter = this.onEnter.bind(this); 
    this.onLeave = this.onLeave.bind(this); 
  } 

  onEnter({ currentPosition }){ 
    console.log(currentPosition) 
    if (currentPosition === Waypoint.inside){ 
      this.setState({ isInView: true }); 
    } 
  } 

  onLeave({ currentPosition }){ 
    console.log(currentPosition) 
    // Fixed: Use the parameter currentPosition instead of this.currentPosition
    if (currentPosition === Waypoint.below){ 
      this.setState({ isInView: false }); 
    } 
  } 

  render(){ 
    return ( 
      <div> 
        <Waypoint onEnter={this.onEnter} onLeave={this.onLeave}></Waypoint> 
        {this.props.children({ isInView: this.state.isInView})} 
      </div> 
    ); 
  } 
} 

export default WhenInView;

Additional Note

Depending on your use case, you might also want to handle Waypoint.above in the onLeave method if you want the div to hide when the waypoint scrolls above the viewport too. Just add an OR condition:

if (currentPosition === Waypoint.below || currentPosition === Waypoint.above) {
  this.setState({ isInView: false });
}

内容的提问来源于stack exchange,提问作者ebbandflows

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 07:11:04