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
相关产品推荐
相关产品推荐

