美文网首页
Vue&React以ES6的Class语法来创建组件

Vue&React以ES6的Class语法来创建组件

作者: 睦月MTK | 来源:发表于2020-05-11 16:37 被阅读0次

声明:将以一个钟表组件作为例子


Vue

class MtkClock {
    constructor(){
        this.data = this.dataInit
        this.methods = {
            tick: this.tick
        }
        this.mounted = this.componentDidMount
        this.beforeDestroy = this.componentWillUnmount
        this.render = this.render_vue
    }

    dataInit(){
        return {
            date: new Date(),
            timer: null,
        }
    }

    tick() {
        this.date = new Date()
    }

    componentDidMount(){
        this.timer = setInterval(() => this.tick(), 1000)
    }

    componentWillUnmount(){
        clearInterval(this.timer);
    }

    render_vue(){
        return (
            <p>{this.date.toLocaleTimeString()}</p>
        )
    }
}

React

import React from 'react';

class MtkClock extends React.Component{
    constructor(props){
        super(props)
        this.state = this.dataInit()
    }

    dataInit(){
        return {
            date: new Date(),
            timer: null,
        }
    }

    tick() {
        this.setState(() =>{return {date : new Date()};});   
    }

    componentDidMount(){
        this.timer = setInterval(() => this.tick(), 1000)
    }

    componentWillUnmount(){
        clearInterval(this.timer);
    }

    render(){
        return (
            <p>{this.state.date.toLocaleTimeString()}</p>
        )
    }
}

注意:
(1) React会将以小写字母开头的组件视为原生 DOM 标签,故组件名称必须以大写字母开头


参考文档:

相关文章

网友评论

      本文标题:Vue&React以ES6的Class语法来创建组件

      本文链接:https://www.haomeiwen.com/subject/msounhtx.html