关于react中的bind事件绑定

2018-10-01  本文已影响0人  欧皇喜羊羊

自己发现在学习写React项目时,在某个组件上都会用到bind进行事件绑定比如

<Button type="primary" htmlType="button" onClick={this.addUserCollection.bind(this)}>收藏该文章</Button>

一直不明白到底是什么意思,现在初步记录一下,bind()函数给出的解释为:
bind()方法会创建一个新函数,当这个新函数被调用时,它的this值是传递给bind()的第一个参数, 它的参数是bind()的其他参数和其原本的参数.

在网友那找到的下面这个例子就十分清晰地解释了这个问题:

this.x = 9; 
var module = {
  x: 81,
  getX: function() { return this.x; }
};

module.getX(); // 返回 81

var retrieveX = module.getX;
retrieveX(); // 返回 9, 在这种情况下,"this"指向全局作用域

// 创建一个新函数,将"this"绑定到module对象
// 新手可能会被全局的x变量和module里的属性x所迷惑
var boundGetX = retrieveX.bind(module);
boundGetX(); // 返回 81

即使用bind()方法是为了将函数中的this与当前组件绑定,在该处理函数中的this时刻都指向该组件,避免出现问题。

同时,如今进行this绑定除了bind外还有其他两种方式

构造函数内绑定

在构造函数 constructor 内绑定this,好处是仅需要绑定一次,避免每次渲染时都要重新绑定,函数在别处复用时也无需再次绑定

import React, {Component} from 'react'

class Test extends React.Component {
    constructor (props) {
        super(props)
        this.state = {message: 'Allo!'}
        this.handleClick = this.handleClick.bind(this)
    }

    handleClick (e) {
        console.log(this.state.message)
    }

    render () {
        return (
            <div>
                <button onClick={ this.handleClick }>Say Hello</button>
            </div>
        )
    }
}
箭头函数方式

箭头函数则会捕获其所在上下文的this值,作为自己的this值,使用箭头函数就不用担心函数内的this不是指向组件内部了。可以按下面这种方式使用箭头函数:


class Test extends React.Component {
    constructor (props) {
        super(props)
        this.state = {message: 'Allo!'}
    }

    handleClick (e) {
        console.log(this.state.message)
    }

    render () {
        return (
            <div>
                <button onClick={ ()=>{ this.handleClick() } }>Say Hello</button>
            </div>
        )
    }
}

参考文献

React事件处理函数中绑定this的bind()函数
React绑定this的三种方式

上一篇 下一篇

猜你喜欢

热点阅读