当用户到达页面底部然后向上滚动时,React 抛出错误“TypeError: _this.setState is not a function”
这是一个检查客户端位置的滚动处理程序。如果客户端位于页面的主页部分,它会更新状态 {active: 'home'}。然后,导航栏组件重新呈现并为 home-navlink 提供事件类。
class Navbar extends Component {
constructor(){
super();
this.state = {
active: 'home'
};
this.handleScroll = this.handleScroll.bind(this);
}
componentDidMount(){
document.addEventListener('scroll', this.handleScroll);
}
componentWillUnmount(){
document.removeEventListener('scroll', this.handleScroll);
}
//offset values are location of elements minus the navbar (10vh)
handleScroll = ()=>{
let wind = window.pageYOffset;
let tenVh = window.innerHeight / 10;
let offset = {
home: document.getElementById('home').offsetTop - tenVh,
tech: document.getElementById('tech').offsetTop - tenVh,
projects: document.getElementById('projects').offsetTop - tenVh,
contact: document.getElementById('contact').offsetTop - tenVh,
};
if (wind < offset.tech){
if (this.state.active !== 'home' ){
this.setState({
active: 'home'
});
}
} else if (wind > offset.tech && wind < offset.projects){
if (this.state.active !== 'tech' ){
this.setState({
active: 'tech'
});
}
} else if ( wind > offset.projects && wind < offset.contact ){
if (this.state.active !== 'projects' ){
this.setState({
active: 'projects'
});
}
} else if (wind > offset.contact){
if (this.state.active !== 'contact' ){
this.setState = ({
active: 'contact'
});
}
}
}
render(){
return(
<div className="navbar" >
<div className="navbrand">
<a href="#home">
<img src={brand} alt='pig brand' />
LtP</a>
</div>
<div className="link-ctr">
<a href="#home" className={
(this.state.active ==='home')?'active':null}>Home</a>
<a href="#tech" className={
(this.state.active === 'tech')?'active':null}>Tech</a>
<a href="#projects" className={
(this.state.active === 'projects')?'active':null}>Projects</a>
<a href="#contact" className={
(this.state.active === 'contact')?'active':null}>Contact</a>
</div>
</div>
)
}
}
最佳答案
改变
this.setState = ({
active: 'contact'
});
到
this.setState({
active: 'contact'
});
构造函数中也不需要以下内容,因为 handleScroll 是箭头函数,所以箭头函数不需要手动绑定(bind)
this.handleScroll = this.handleScroll.bind(this);
关于javascript - React : setState is return an error in a scroll handler. 是什么破坏了它?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53919307/