【发布时间】:2019-06-14 16:04:13
【问题描述】:
当您在元素上方滚动 100 像素或更少时,我希望 div 元素获得“showtext”类。当您高于它 100 像素或更多时,它具有“隐藏”类。
我正在尝试使用 ref 来访问 div 元素,并使用一种名为 showText 的方法来检查并查看我们何时滚动到该 div 元素上方 100 像素或更小,我正在为此使用 scrollTop。
然后我使用componentDidMount添加一个滚动的窗口事件监听器,并调用我的showText方法。
我是新手,所以我确信这里有错误并且可能是错误的代码。但任何帮助表示赞赏!
import React, {Component} from 'react';
class SlideIn extends Component{
state={
showTexts: false,
}
showText=()=>{
const node= this.showTextRef;
if(node.scollTop<=100)
this.setState({
showTexts: true
})
}
componentDidMount(){
window.addEventListener('scroll', this.showText() )
}
render(){
const intro= document.querySelector('.intro')
return(
<div classname={this.state.showTexts ? 'showText' : 'hidden'} ref={node =>this.showTextRef = node}>
{window.addEventListener('scroll', this.showText)}
<h1>You did it!</h1>
</div>
)
}
}
export default SlideIn
我曾尝试在我的窗口滚动事件中使用 this.showText,正如您在 this.showText() 上方看到的,两者都没有奏效。我试图在我的 showText 方法中使用我的 div ref 上的 current 属性,它抛出了一个错误,说 scrollTop 无法定义 null 的属性。
我还是新手,从来没有以这种方式添加窗口事件侦听器,也从未使用过 scrollTop。
感谢您的帮助!
【问题讨论】:
标签: javascript reactjs