反应中箭头功能的等效不起作用

时间:2017-10-02 14:58:46

标签: reactjs

我有一个组件:

class ProbaShell extends React.Component{
constructor(props){
    console.log('constructorStart');
    super(props);

this.state = {
    h:   5,
    w: 500
    };    
this.fadeIn1 = this.fadeIn1.bind(this);
}


fadeIn1() { 
        const interval = setInterval(function(){
            this.setState({ h: (this.state.h + 5) });
            if (this.state.h >= 400) {
                clearInterval(interval);
            } 
        },50);   
    }

fadeIn() {
    const interval = setInterval(() => {
        this.setState({ h: (this.state.h + 5) });     
        if (this.state.h >= 400) {
            clearInterval(interval);
        } 
    }, 50);   
}

render(){
    console.log('render')
    return(
        <Proba style={{height: this.state.h}}/>
    )
}

componentDidMount(){
    console.log('compDidMount');
    this.fadeIn();
}
}

它与fadeIn函数完美配合,但不与fadeIn1配合使用。我弄不清楚为什么?我已经阅读了一篇关于使用它的文章,但仍然不明白为什么?

2 个答案:

答案 0 :(得分:3)

通过使用胖箭头=>,它将自动将其作为具有上下文的类方法绑定。 function(){..}不会发生这种情况,因此您必须通过执行

手动绑定它
constructor(props){
    console.log('constructorStart');
    super(props);
    this.fadeIn1 = this.fadeIn1.bind(this);
}

并将上下文传递给函数,例如

fadeIn1() {
    const interval = setInterval(function() {
        this.setState({
            h: (this.state.h + 5)
        });
        if (this.state.h >= 400) {
            clearInterval(interval);
        }
    }.bind(this), 50);
}

您可以阅读有关Handling Events in React的更多信息,尽管这更具针对性。

答案 1 :(得分:0)

这不起作用,因为在javascript中这是动态的。 setInterval实际上是window.setInterval所以在函数内部,这将是window。箭头函数不仅仅是语法糖,它们实际上并没有重新定义它。

相关问题