我是 React.js 的新手。我试图让左侧导航保持滚动。出于某种原因,当我滚动时,下面的代码会导致以下错误:
未捕获的类型错误:this.setState 不是一个函数
任何帮助都会很棒!谢谢
class Sticky extends React.Component {
constructor(props) {
super(props);
this.state = {
scrollingLock: false
};
}
componentDidMount(){
window.addEventListener('scroll', this.handleScroll);
}
componentWillUnmount() {
window.removeEventListener('scroll', this.handleScroll);
}
handleScroll() {
if (window.scrollY > 100) {
console.log("should lock");
this.setState({
scrollingLock: true
});
} else if (window.scrollY < 100) {
console.log("not locked" );
this.setState({
scrollingLock: false
});
}
}
render() {
return (
<div style={{ width: "100%", position: this.state.scrollingLock ? "fixed" : "relative"}}>
{this.props.children}
</div>
)
}
}
export default Sticky;
最佳答案
此代码应该适合您。
class Sticky extends React.Component {
constructor(props) {
super(props);
this.state = {
scrollingLock: false
};
// example how to bind object in React ES6
this.handleScroll = this.handleScroll.bind(this)
}
componentDidMount(){
window.addEventListener('scroll', this.handleScroll);
}
componentWillUnmount() {
window.removeEventListener('scroll', this.handleScroll);
}
handleScroll() {
if (window.scrollY > 100) {
console.log("should lock");
this.setState({
scrollingLock: true
});
} else if (window.scrollY < 100) {
console.log("not locked" );
this.setState({
scrollingLock: false
});
}
}
render() {
return (
<div style={{ width: "100%", position: this.state.scrollingLock ? "fixed" : "relative"}}>
{this.props.children}
</div>
)
}
}
React.render(<Sticky/> , document.body)
还有 here是一篇关于 ES6 React 代码中绑定(bind)的好文章。
希望对您有所帮助。
谢谢
关于javascript - React.js 粘性导航不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33555021/