首页 > 其他 > 详细

react--绑定this三种方式

时间:2019-04-11 16:26:34      阅读:99      评论:0      收藏:0      [点我收藏+]

技术分享图片

在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带参数跳转路由的方法;

react--绑定this三种方式

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

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!