ReactJS lifecycle method inside a function Component

前端 未结 8 575
一生所求
一生所求 2020-11-30 19:28

Instead of writing my components inside a class, I\'d like to use the function syntax instead.

How do I override componentDidMount, componentWillM

8条回答
  •  [愿得一人]
    2020-11-30 20:17

    You can make use of create-react-class module. Official documentation

    Of course you must first install it

    npm install create-react-class
    

    Here is a working example

    import React from "react";
    import ReactDOM from "react-dom"
    let createReactClass = require('create-react-class')
    
    
    let Clock = createReactClass({
        getInitialState:function(){
            return {date:new Date()}
        },
    
        render:function(){
            return (
                

    {this.state.date.toLocaleTimeString()}

    ) }, componentDidMount:function(){ this.timerId = setInterval(()=>this.setState({date:new Date()}),1000) }, componentWillUnmount:function(){ clearInterval(this.timerId) } }) ReactDOM.render( , document.getElementById('root') )

提交回复
热议问题