react学习历程8——标准类组件示例

题目:页面输出【学习react】点击切换为【学习vue】,点击来回切换

class Study extends React.Component {
    constructor(props) {
        super(props);
        this.state = {frameType: false};
        this.tick = this.tick.bind(this);
    }

    tick() {
        this.setState({frameType: !this.state.frameType});
    }

    render() {
        const frameType = this.state.frameType;
        return (<div onClick={this.tick}><h2>学习{frameType ? 'react' : 'vue'}</h2></div>)
    }
}

标准的写法注意点:

  • 类组件的方法都是事件行为
  • 类组件中的方法不能使用this,必须绑定类,
    this.tick = this.tick.bind(this);
  • render能使用this是因为react框架默认已经绑定好了
  • render中使用的事件行为tick,不是类中的方法tick,而是类属性tick。绑定事件中的this.tick

标红的举例如下

class Study extends React.Component {
    constructor(props) {
        super(props);
        this.state = {frameType: false};
        this.change = this.tick.bind(this);
    }

    tick() {
        this.setState({frameType: !this.state.frameType});
    }

    render() {
        const frameType = this.state.frameType;
        return (<div onClick={this.change}><h2>学习{frameType ? 'react' : 'vue'}</h2></div>)
    }
}

这个得知道,但一般我们写代码的时候,都重名就可以了

下面对该标准写法做优化处理

class Study extends React.Component {

    state={frameType:false};
    
    tick=()=>{
        this.setState({frameType: !this.state.frameType});
    }

    render() {
        const frameType = this.state.frameType;
        return (<div onClick={this.tick}><h2>学习{frameType ? 'react' : 'vue'}</h2></div>)
    }
}
  • 箭头函数有一个重要的特点,是自身没有this,但可以使用this,它会往上找this,哪怕找到windows,但绝不会是undefined。所以在组件类中定义事件行为的时候,使用箭头函数,this就是指向该组件实例了。
  • 类有一个基本概念,属性可以直接在类中定义,而不需要在构造函数中定义。所以state也可以直接写在类中
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值