首页 > 解决方案 > 从“扩展组件”更改为“createReactClass”

问题描述

我在 react 中实现了以下计时器,它使用“扩展组件”的旧实现方式。我仍在为如何使用“createReactClass”来实现这一点而苦苦挣扎。应该如何适应?

import React, { Component } from 'react'

class Timer extends Component {
  constructor (props) {
    super(props)
    this.state = {
      count: 1
    }
  }

  render () {
    const {count} = this.state
    return (
      <div>
        <h1>Current Count: {count}</h1>
      </div>
    )
  }
  // setInterval
  // clearInterval
  componentDidMount () {
    const {startCount} = this.props
    this.setState({
      count: startCount
    })
    this.doIntervalChange()
  }

  doIntervalChange = () => {
      this.myInterval = setInterval(() => {
      this.setState(prevState => ({
        count: prevState.count - 1
      }))
    }, 1000)
  }

  componentWillUnmount () {
    clearInterval(this.myInterval)
  }
}

export default Timer

提前致谢!

标签: javascriptreactjsfrontendweb-frontend

解决方案


推荐阅读