react绑定this三种方式

在pages下新增this.js文件并修改route/index.js如下

this.js

import React from 'react';

export default class This extends React.Component{
    constructor(){
        super();
        this.state = {
            value: ''
        };

        this.changeValue1 = this.changeValue1.bind(this);
    }

    changeValue1(){
        this.setState({
            value: 'changeValue1'
        });
    }

    changeValue2 = () => {
        this.setState({
            value: 'changeValue2'
        });
    };

    changeValue3(){
        this.setState({
            value: 'changeValue3'
        });
    }


    render(){
        return (
            <div>
                <p onClick={this.changeValue1}>this1</p>
                <p onClick={this.changeValue2}>this2</p>
                <p onClick={this.changeValue3.bind(this)}>this3</p>
                <p>{this.state.value}</p>
            </div>
        )
    }
}

route/index.js

import React from 'react';
import {Switch, Route} from "react-router-dom";

import Home2 from '../pages/Home2';
import OnePage from '../pages/OnePage';
import TwoPage from '../pages/TwoPage';
import This from '../pages/This';

const Routers = (
    <Switch>
        <Route path="/" exact component={Home2} />
        <Route path="/onePage" component={OnePage} />
        <Route path="/twoPage/:id" component={TwoPage} />
        <Route path="/this" component={This} />
    </Switch>
);

export default Routers

第一种绑定this方式是bind(this) 

第二种使用ES6的箭头函数

第三种方式好像和第一种一样?其实如果要加参数的话我更推荐第三种,因为:

<p onClick={this.changeValue3.bind(this, 666)}>this3</p>  
changeValue3(id){
    this.setState({
        value: 'changeValue3'
    });
    this.props.history.push(`/twoPage/${id}`)
}
添加参数id为666并补上上一篇提到的js带参数跳转路由的方法;

原文地址:https://www.cnblogs.com/huangjie2018/p/10690471.html