React之类组件与函数组件

类组件

所谓类组件,就是用ES6的class来定义组件

定义类组件

import React, { Component } from "react";

export default class MyComponent extends Component {
    constructor(props) {
        super(props);
        this.state = {
            hello: "hello world",
        };
    }

    handleClick = () => {
        this.setState({hello:"hello react"})
    }

    render() {
        const { hello } = this.state;
        return (
            <>
                <div>{hello}</div>
                {/* 不需要加括号 */}
                <button onClick={this.handleClick}>点击修改</button>
            </>
        );
    }
}

类组件中的函数

  • 上面例子中所使用的函数是箭头函数,众所周知,箭头函数没有this,那么这里的this就是使用的外部的this,实例化之后也就是指,实例化之后的对象
  • 所以,如果不用箭头函数来定义函数的话,需要在constructor绑定一下this
constructor(props) {
    super(props);
    this.state = {
        hello: "hello world",
    };
    this.handleClick = this.handleClick.bind(this)
}

handleClick(){
    this.setState({hello:"hello react"})
}

函数组件

  • 在react-hooks之前,函数组件本身没有this,所以自身不能存放状态,一般用于传递数据进行展示

函数组件

export default function MyComponent2(){
    console.log(this);
    return <div>Hello,函数组件</div>
}

我们打印this,就会发现他是undefined

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值