Javascript 在react中滚动时未更改类
下面是我的Javascript 在react中滚动时未更改类,javascript,reactjs,ecmascript-6,scroll,dom-events,Javascript,Reactjs,Ecmascript 6,Scroll,Dom Events,下面是我的handleScroll函数,我试图在其中添加red类,如果它向下滚动到某个限制,则应用blue。然而,这只是进入else语句和console.log(e.target.scrollTop)中其控制台为未定义。让我知道我做错了什么 代码- handleScroll(e) { console.log(e.target.scrollTop); if (window.screenX > 100) { this.setState({ navBc
handleScroll
函数,我试图在其中添加red
类,如果它向下滚动到某个限制,则应用blue
。然而,这只是进入else
语句和console.log(e.target.scrollTop)中代码>其控制台为未定义
。让我知道我做错了什么
代码-
handleScroll(e) {
console.log(e.target.scrollTop);
if (window.screenX > 100) {
this.setState({
navBckgroundColor: `red`
});
} else {
this.setState({
navBckgroundColor: `blue`
});
}
}
代码沙盒-请使用
handleScroll = e => {
console.log(e.target.scrollTop);
if (window.scrollY > 100) {
this.setState({
navBckgroundColor: `red`
});
} else {
this.setState({
navBckgroundColor: `blue`
});
}
}
请参见以下可用代码:
https://codesandbox.io/s/friendly-swirles-bwl06
此外,window.screenX将始终输出相同的值,因此不会更改颜色
我在代码中也改变了这一点使用window.scrollY
而不是window.screenY
,并绑定handleScroll方法
handleScroll = (e) => {
if (window.scrollY > 100) {
this.setState({
navBckgroundColor: `red`
});
} else {
this.setState({
navBckgroundColor: `blue`
});
}
}
我强烈建议在您的病情中增加额外的检查。当您滚动一次时,您会在特定范围(100)后多次更新组件状态,这是不必要的。你只需要更新一次
它将不断更新,因为您满足了handleScroll
中的条件,即使背景已经更改。更新量过大可能会导致应用程序崩溃
尝试这样的操作,它将按预期更新组件状态,并且仅在必要时更新:
类应用程序扩展了React.Component{
建造师(道具){
超级(道具);
此.state={
navBckgroundColor:`blue`,
更改:错误
};
}
componentDidMount(){
window.addEventListener(“滚动”,this.handleScroll);
}
//改用arrow函数,使其“this”关键字指向组件的执行上下文。否则,“this”将指向全局窗口对象,您不能在其中使用this.setState。
handleScroll=e=>{
如果(window.pageYOffset>100&&!this.state.changed){
这是我的国家({
navBckgroundColor:`red`,
是的
});
}else if(window.pageYOffset<100&&this.state.changed){
这是我的国家({
navBckgroundColor:`blue`,
更改:错误
});
}
};
render(){
返回(
你好,代码沙盒
开始编辑,看看神奇的发生!
);
}
}
这项工作顺利吗?:)@ChristophenGo啊抱歉..我的系统崩溃..upvoteddarn我希望你能保留所有文件:)
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
navBckgroundColor: `blue`,
altered: false
};
}
componentDidMount() {
window.addEventListener("scroll", this.handleScroll);
}
//use arrow function instead so that its "this" keyword points to the component's execution context. Otherwise, "this" will point to the global window object where you cannot use this.setState.
handleScroll = e => {
if (window.pageYOffset > 100 && !this.state.altered) {
this.setState({
navBckgroundColor: `red`,
altered: true
});
} else if(window.pageYOffset < 100 && this.state.altered) {
this.setState({
navBckgroundColor: `blue`,
altered: false
});
}
};
render() {
return (
<div className="App">
<Navbar bckGroundColor={this.state.navBckgroundColor} />
<h1>Hello CodeSandbox</h1>
<h2>Start editing to see some magic happen!</h2>
</div>
);
}
}