关于react中的绑定问题

首先我们建立一个按钮计数的例子来解释react中的绑定问题

index.html

.....
<body>
<div id="container"></div>
<script src=../src/index.js></script>
</body>
.....

index.js

class Counter extends Component {
    constructor(props){
        super(props);
    }
    render(){
        
        const textStyle = {
            fontSize: 72,
            fontFamily: "sans-serif",
            color: '#333',
            fontWeight: 'bold'
        };
        
        return(
            <div style={textStyle}>
                {this.props.display}
            </div>
        );
    }
}

class CounterParent extends Component{
    
    constructor(props){
        super(props);
        this.state = {
            count:0
        };
    }
    increase() {
        console.log("plus 1");
        this.setState({
            count: this.state.count + 1
        });
    }
    
    render(){
        var backgroundStyle = { 
            padding: 50, 
            backgroundColor: "#FFC53A", 
            width: 250, 
            height: 100, 
            borderRadius: 10, 
            textAlign: "center" };
        var buttonStyle = { 
            fontSize: "1em", 
            width: 30, 
            height: 30, 
            fontFamily: "sans-serif", 
            color: "#333", 
            fontWeight: "bold", 
            lineHeight: "3px" };
        
        return(
            <div style={backgroundStyle}>
                <Counter display={this.state.count}/>
                <button onClick={this.increase} style={buttonStyle}>+</button>
                
            </div>
        
        );
}
}
ReactDOM.render(<CounterParent/>,document.getElementById('container');

如此,代码便能成功运行,如下图所示:

但是单击按钮之后,却会报错,为什么呢?
其实这是一个比较简单的问题,让我们看一下下面这部分代码。

increase() {
        console.log("plus 1");
        this.setState({
            count: this.state.count + 1
        });
    }
    
render(){
.....
    return(
        <div style={backgroundStyle}>
            <Counter display={this.state.count}/>
            <button onClick={this.increase} style={buttonStyle}>+</button>    
            </div>
        );
}

让我们再看一下报错:
Uncaught TypeError: Cannot read property ‘setState’ of undefined

原因是,当我们给按钮绑定动作时,我们使用了this.increase, 而由于我们没有对increase方法进行绑定,因此,在increase内部,this指针指向的不是我们所创建的组件,而是window,而window并没有setState()方法,因此便会报错。

解决方法

方法1:在CounterParent 的构造函数中就对increase 进行绑定
即在构造函数中加入

        this.increase=this.increase.bind(this);

方法2:把increase函数改为箭头函数

increase=()=> {
        this.setState({
            count: this.state.count + 1
        });
    }

因为箭头函数不会改变this原本的绑定,因此我们的组件可以正确的调用increase函数。

方法3: 在设置按钮时使用箭头函数

<button onClick={()=>this.increase()} style={buttonStyle}>+</button>

理由如上,若对箭头函数不了解可以看一下这篇文章

本人能力有限,若有说的不对的地方,欢迎指正
也欢迎大家与我交流技术问题

发布了5 篇原创文章 · 获赞 0 · 访问量 73

猜你喜欢

转载自blog.csdn.net/weixin_41276957/article/details/84036864