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帶參數跳轉路由的方法;


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM