【react】jsx中,解决事件处理程序 this指向问题

本文介绍了在React中,由于内部事件处理导致的函数中this变为undefined的问题,以及三种解决方法:1) 使用箭头函数;2) 在构造函数中使用bind(this);3) 直接将方法定义为箭头函数。这些方法确保在事件处理程序中正确设置this,以便能够访问组件的状态并更新它。
摘要由CSDN通过智能技术生成

// 是react 内部监听到了 你点击了, 然后对 函数进行了一个回调,react 内部 并且给 这个函数的this 更改为 undefined

class Hello extends React.Component {
    state = {
        count: 0,

    }
    handleSum() {
        // 事件处理程序中的 this 是 undefined
		// 这个方法其实是 react 内部调用 , 内部调用的时候,没有 正确绑定 this
		        // 是react 内部监听到了 你点击了,  然后对 函数进行了一个回调,react 内部 并且给 这个函数的this 更改为 undefined
    }
    render() {
        return (
            <div>
                <h1>计数器: {this.state.count}</h1>
                <button onClick={this.handleSum}>+1</button>
            </div>
        )
    }

}

解决方法

1、箭头函数方法

<button onClick={() => { this.handleSum() }}>+1</button>

class Hello extends React.Component {
    state = {
        count: 0,

    }
    handleSum() {
        // 事件处理程序中的 this 是 undefined
        this.setState({
            // 要修改那个数据,就把那个数据放进来就可以
            count: this.state.count + 1
        })
    }
    render() {
        return (
            <div>
                <h1>计数器: {this.state.count}</h1>
                <button onClick={() => { this.handleSum() }}>+1</button>
            </div>
        )
    }

}

2、Function.prototype.bind()

class Hello extends React.Component {
    constructor() {
        super()
        this.handleSum = this.handleSum.bind(this)
    }
    state = {
        count: 0,

    }
    handleSum() {
        // 事件处理程序中的 this 是 undefined
        this.setState({
            // 要修改那个数据,就把那个数据放进来就可以
            count: this.state.count + 1
        })
    }
    render() {
        return (
            <div>
                <h1>计数器: {this.state.count}</h1>
                {/* <button onClick={() => { this.handleSum() }}>+1</button> */}
                // 第一种
                <button onClick={this.handleSum}>+1</button>
            	// 也可以不用再 constructor 中调用,直接 onClick={this.handleSum.bind(this)}
            </div>
        )
    }

}

3、实例方法

class Hello extends React.Component {
    state = {
        count: 0,

    }
    handleSum = () => {
        // 事件处理程序中的 this 是 undefined
        this.setState({
            // 要修改那个数据,就把那个数据放进来就可以
            count: this.state.count + 1
        })
    }
    render() {
        return (
            <div>
                <h1>计数器: {this.state.count}</h1>
                <button onClick={this.handleSum}>+1</button>
            </div>
        )
    }

}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值