2017-07-24 13 views
0

我想通過從狀態道具通過定位修復,但我不能setState裏面handleScroll功能。我不知道如何訪問函數內部的狀態。滾動addeventlistener裏面的訪問類道具

class App extends Component { 

    state = { fixed: false } 

    componentDidMount() { 
    window.addEventListener('scroll', this.handleScroll); 
    } 

    componentWillUnmount() { 
    window.removeEventListener('scroll', this.handleScroll); 
    } 

    handleScroll(e) { 
    let scrollTop = e.srcElement.body.scrollTop; 
    (scrollTop > 0) ? this.setState({ fixed: true }) : this.setState({ fixed: false }); 
    } 

    render() { 
    // grab steps 
    const { steps } = this.props; 
    const { fixed } = this.state; 
    const { scrollToStep } = this; 

    return ce('div', { className:'allTheSteps' }, 
     ce(pagination, { steps, fixed }), 
     Object.values(steps).map((step, i) => 
     ce(Steps, { step, key: v4(), i }), 
    ) 
    ); 
    }; 

}; 

回答

1

您需要綁定handleScroll方法:

class App extends Component { 

    constructor(props) { 
    super(props); 
    this.handleScroll = this.handleScroll.bind(this); 
    } 

    ... 

}; 
0

你的回調是在錯誤的範圍內執行。你必須將它綁定到正確的範圍。要做到這一點,你可以使用ES6箭頭函數,並且你的方法應該被綁定,而不必手動完成。 在你的例子中:

... 
    componentDidMount() { 
     window.addEventListener('scroll', (e) => this.handleScroll(e)); 
    } 

    componentWillUnmount() { 
     window.removeEventListener('scroll', (e) => this.handleScroll(e)); 
    } 
... 
相關問題