[英]React.js sticky nav not working
我是React.js的新手。 我正試圖讓左側導航系統堅持滾動。 由於某種原因,下面的代碼滾動時導致以下錯誤:
未捕獲的TypeError: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)
這里還有一篇關於ES6 React Code中綁定的好文章。
我希望它會對你有所幫助。
謝謝
您應該使用Function.prototype.bind()
將方法和實例放在一個函數中。 我建議你將綁定函數保存為如下屬性:
class Sticky extends React.Component {
constructor(props) {
...
this._handleScroll = this.handleScroll.bind(this);
}
componentDidMount(){
window.addEventListener('scroll', this._handleScroll);
}
componentWillUnmount() {
window.removeEventListener('scroll', this._handleScroll);
}
..
}
React組件不會與ES6類自動綁定。 因此,您手動綁定實例及其方法。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.