1.1.0 • Published 6 years ago

react-bind-once v1.1.0

Weekly downloads
1
License
MIT
Repository
-
Last release
6 years ago

react-bind-once

node npm license

安装

$ npm install react-bind-once --save

使用

import React, { Component } from 'react';
import bindOnce from 'react-bind-once';

class App extends Component {
    constructor(props) {
        super(props);
        bindOnce(this);
    }

    handleClick() {
        console.log('clicked');
    }

    render() {
        return (
            <button onClick={this.handleClick}>Click</button>
        );
    }
}

export default App;

背景

绑定到JSX上的事件句柄,最终会变成事件监听的回调,而回调是指向全局作用域的

而我们需要事件句柄指向组件实例,因为里面可能会访问组件实例的属性

使JSX事件句柄的this指向组件实例的方式有四种:

在JSX里面直接绑定this

这样的问题是每次触发事件都要重新绑定一次

handleClick() {
    console.log('clicked');
}

render() {
    return (
        <button onClick={this.handleClick.bind(this)}>Click</button>
    );
}

包裹一层箭头函数

箭头函数没有this,会保留上级上下文,所以会指向组件实例

这样的问题是每次触发事件都会创建一个箭头函数

handleClick() {
    console.log('clicked');
}

render() {
    return (
        <button onClick={() => this.handleClick()}>Click</button>
    );
}

在构造函数里手动绑定,这是React官方推荐的方式

但是每一个事件句柄都要在构造函数手动绑定,很麻烦

而且这样做的后果就是方法会同时存在于实例和原型上

等号右边的this.handleClick是从原型上获得的

但是等号左边,程序会以为你想赋值给实例

所以实例上有一份该方法,原型上也有一份该方法

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

handleClick() {
    console.log('clicked');
}

render() {
    return (
        <button onClick={this.handleClick}>Click</button>
    );
}

方法直接写在实例上

这种方式兼具性能和优雅

但是必须要写成箭头函数,如果写成普通函数,this仍然指向undefined

react-bind-once推荐这种写法

当然bindOnce(this)似乎更简单一些

handleClick = () => {
    console.log('clicked');
}

render() {
    return (
        <button onClick={this.handleClick}>Click</button>
    );
}

利益

使用react-bind-once会自动帮你把在原型上的方法绑定this到组件实例

只需要在constructor上执行一次bindOnce(this)即可,就像它的名字描述的一样

有些方法不是事件句柄不也自动绑定了么?

是的,对于这样一个足够简单的工具,配置项完全是多余的

性能最优,足够简单

License

MIT