react里面的this指向解决方案

1. 箭头函数

import React from "react"
class Hellow extends React.Component{
    constructor(){
        super()
        this.handulclick2 = this.handulclick2.bind(this)
    }
    state={
        msg:"箭头函数"
    }
    render(){
        return(
            <div>
                {/* 箭头函数 */}
                <input type="button" value="测试1" onClick={()=>this.handulclick1()} /> 
                 {/*bind方式  */}
                <input type='button' value="测试" onClick={this.handulclick2.bind(this)} /> 
                {/* 实例方法 必须要babel */}
                <input type='button' value="测试" onClick={this.handulclick3} />       
            </div>
        )
    }
    handulclick1(){
        console.log(this.state.msg)
    }
    handulclick2(){
        console.log(this.state.msg)
    }
    handulclick3=()=>{
        console.log(this.state.msg)
    }
}
export default Hellow
发布了109 篇原创文章 · 获赞 23 · 访问量 10万+

猜你喜欢

转载自blog.csdn.net/xy19950125/article/details/97642940
今日推荐