react之事件绑定(this、传参)

一、事件绑定函数中this

默认情况下,this指向undefined

import React from 'react'
export default class ThingBind extends React.Component{
    constructor(){
        super()
    }
    console(){
        console.log(this)//输出undefined
    }
    render(){
        return(
        <button onClick={this.console}>点击</button>
        )
    }
}

但实际开发中,我们需要事件函数中的this指向当前组件对象,有下面几种解决方案
第一种:声明函数时候使用箭头函数

import React from 'react'
export default class ThingBind extends React.Component{
    constructor(){
        super()
    }
    console=()=>{
        console.log(this)//输出ThingBing{...}
    }
    render(){
        return(
        <button onClick={this.console}>点击</button>
        )
    }
}

第二种:使用bing,在构造函数中绑定this或者直接在绑定事件时绑定this

import React from 'react'
export default class ThingBind extends React.Component{
    constructor(){
        super()
        this.console=this.console.bind(this)
    }
    console(){
        console.log(this)//输出ThingBing{...}
    }
    render(){
        return(
        <button onClick={this.console}>点击</button>
        // <button onClick={this.console.bind(this)}>点击</button>
        )
    }
}

二、传参

第一种:绑定事件时候使用箭头函数

import React from 'react'
export default class ThingBind extends React.Component{
    constructor(){
        super()
    }
    console(msg){
        console.log(msg)//我是参数
    }
    render(){
        return(
        <button onClick={()=>this.console('我是参数')}>点击</button>
        )
    }
}

第二种:/2.通过bind修改this并且传参

import React from 'react'
export default class ThingBind extends React.Component{
    constructor(){
        super()
    }
    console(msg){
        console.log(msg)//我是参数
    }
    render(){
        return(
        <button onClick={(this.console.bind(this,'我是参数'))}>点击</button>
        )
    }
}

猜你喜欢

转载自blog.csdn.net/qq_42944436/article/details/105056171
今日推荐