类组件this(react)

一、事件绑定
1、普通事件
如果只是普通的事件绑定,不需要传参,事件方法内部也不需要使用 this。

export default class ClassComponent extends Component {
    clickEvent() {
        console.log('这是类组件的事件');
    }

    render() {
        return (
            <>
                <h1>这是一个类组件</h1>
                <button onClick={this.clickEvent}>按钮</button>
            </>
        )
    }
}

2、事件传参、事件方法内部使用 this
如果事件触发时,需要给事件函数传递参数,或者在事件方法中需要使用 this:

import { Component } from 'react'

export default class ClassComponent extends Component {
    getParams(params) {
        console.log('类组件组件的事件接收参数', params);
        this.sayHello()
    }
    sayHello() {
        console.log('hello')
    }
    render() {
        return (
            <>
                <h1>这是类组件</h1>
                <button onClick={() => this.getParams('hello')}>传参按钮</button>
            </>
        )
    }
}

3、事件方法内部使用 this
在不考虑事件传参的情况下,如果只考虑事件方法中需要使用 this:


import { Component } from 'react'

export default class ClassComponent extends Component {
    sayHello = () => {
        this.introduce()
    }
    introduce() {

    }
    render() {
        return (
            <>
                <h1>这是类组件</h1>
                <button onClick={this.sayHello}>this 按钮</button>
            </>
        )
    }
}

二、类组件中 this 的指向

类组件里各个方法中的 this,要判断他们的指向,需要先分析清楚是谁在调用这些方法,谁调用的方法,该方法内部的 this 就指向谁。

1、render 的 this
render 方法是组件实例对象调用的,所以属于 render 函数的 this,指向的永远都是组件实例对象:

import { Component } from 'react'

export default class ClassComponent extends Component {
    render() {
        console.log(this);
        return ()
    }
}

2、事件方法的 this
当 class 中的一个方法,作为了事件的处理函数,这些方法,是点击事件调用的,这个时候该方法中的 this 指向 undefined:

import { Component } from 'react'

export default class ClassComponent extends Component {
    clickEvent() {
        console.log(this);
    }
    render() {
        return (
            <button onClick={this.clickEvent}>按钮</button>
        )
    }
}

3、箭头函数的 this
当 class 中的方法变成了箭头函数,内部的 this 指向的也是组件实例对象:

import { Component } from 'react'

export default class ClassComponent extends Component {
    clickEvent = () => {
        console.log(this);
    }
    render() {
        return (
            <button onClick={this.clickEvent}>按钮</button>
        )
    }
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值