React基础 解决this指向问题

方法1:

高阶函数:通过this 来直接调用 handleClick 并返回箭头函数

柯里化:通过函数调用继续返回函数的形式,实现多次接收参数最后统一处理的函数编码形式

class App extends React.Component {
    state = {
        count: 0,
    }
    handleClick() {
        // 这里的 this 指向是什么?那就看是谁调用的!
        return () => {
            console.log(this.state.count)
        }	
    }
    render() {
        return (
            <div>
                <h2>计数器:{this.state.count}</h2>
                <button onClick={this.handleClick()}>+1</button>
            </div>
        )
    }
}

方法二

包裹一层箭头函数

箭头函数中的 this 指向“外部”,即render 函数,而render 函数中的 this 正是组件实例

class App extends Component {
    state = {
        count: 0,
    }
    handleClick() {
        console.log(this.state.count)
    }
    render() {
        return (
            <div>
                <h2>计数器:{this.state.count}</h2>
                <button onClick={() => this.handleClick()}>+1</button>
            </div>
        )
    }
}

方法三

使用bind

class App extends Component {
    state = {
        count: 0,
    }
    handleClick() {
        console.log(this.state.count)
    }
    render() {
        return (
            <div>
                <h2>计数器:{this.state.count}</h2>
                <button onClick={this.handleClick.bind(this)}>+1</button>
            </div>
        )
    }
}

方法四 (常用)

通过赋值语句往实例上面添加一个箭头函数

class App extends Component {
    state = {
        count: 0,
    }
	//挂载到实例上
    handleClick = () => {
        console.log(this.state.count)
    }
    render() {
        return (
            <div>
                <h2>计数器:{this.state.count}</h2>
                <button onClick={this.handleClick}>+1</button>
            </div>
        )
    }
}

方法五

在构造函数中再创建一个实例方法,和原型方法公用一个函数体

class App extends React.Component {
    constructor() {
        super()
        this.state = {
            count: 0,
        }
        // 1. 往实例自身上又挂载了一个 handleClick 函数
        // 2. 此函数的函数体是通过原型上 handleClick 函数生成的新函数
        // 3. 并把原型上 handleClick 函数中的 this 通过 bind 绑定为了 this,而这里构造函数中的 this 正是实例对象
        // 4. 其实点击的时候调用的是这个构造函数 handleClick(就近原则),而这个构造函数中的 handleClick 执行的是原型上的 handleClick 的函数体
        this.handleClick = this.handleClick.bind(this)
    }
    handleClick() {
        console.log(this.state.count)
    }
    render() {
        return (
            <div>
                <h2>计数器:{this.state.count}</h2>
                <button onClick={this.handleClick}>+1</button>
            </div>
        )
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值