在本节中,我们将学习如何重用和封装一个 Clock 组件。它将设置自己的计时器,并每秒钟更新一次。
我们可以从封装时钟开始:
class Clock extends Component {render () {return (<View><Text>Hello, world!</Text><Text>现在的时间是 {this.state.date.toLocaleTimeString()}.</Text></View>)}}
Clock 现在被定义为一个类,使用类就允许我们使用其它特性,例如局部状态、生命周期钩子。
将生命周期方法添加到类中
在具有许多组件的应用程序中,在销毁时释放组件所占用的资源非常重要。
每当 Clock 组件第一次加载到 DOM 中的时候,我们都想生成定时器,这在 Taro/React 中被称为挂载。
同样,每当 Clock 生成的这个 DOM 被移除的时候,我们也会想要清除定时器,这在 Taro/React 中被称为卸载。
我们可以在组件类上声明特殊的方法,当组件挂载或卸载时,来运行一些代码:
class Clock extends Component {constructor (props) {super(props)this.state = { date: new Date() }}componentDidMount() {}componentWillUnmount() {}render () {return (<View><Text>Hello, world!</Text><Text>现在的时间是 {this.state.date.toLocaleTimeString()}.</Text></View>)}}
这些方法被称作生命周期钩子。
当组件输出到 DOM 后会执行 componentDidMount() 钩子,这是一个建立定时器的好地方:
componentDidMount() {this.timerID = setInterval(() => this.tick(),1000)}
注意我们如何在 this 中保存定时器 ID。
虽然 this.props 由 Taro 本身设置以及 this.state 具有特殊的含义,但如果需要存储不用于视觉输出的东西,则可以手动向类中添加其他字段。
如果你不在 render() 中使用某些东西,它就不应该在状态中。
我们将在 componentWillUnmount() 生命周期钩子中卸载计时器:
componentWillUnmount () {clearInterval(this.timerID)}
最后,我们实现了每秒钟执行的 tick() 方法。
它将使用 this.setState() 来更新组件局部状态:
import Taro, { Component } from '@tarojs/taro'class Clock extends Component {constructor (props) {super(props)this.state = { date: new Date() }}componentDidMount () {this.timerID = setInterval(() => this.tick(),1000);}componentWillUnmount () {clearInterval(this.timerID)}tick () {this.setState({date: new Date()});}render() {return (<View><Text>Hello, world!</Text><Text>现在的时间是 {this.state.date.toLocaleTimeString()}.</Text></View>)}}
