多层div中时间实时更新的实现

state 通过渲染修改 UI,UI 通过事件修改数据流,数据流再次渲染来修改 state

  1. class Clock extends React.Component {
  2. constructor(props) {super(props);
  3. this.state = {date: new Date()};}
  4. componentDidMount() { this.timerID = setInterval(() => this.tick(),1000);}
  5. componentWillUnmount() { clearInterval(this.timerID);}
  6. tick() {this.setState({date: new Date()});}
  7. render() {
  8. return(//如果 hello的 greeting-left-left写成greeting-left,蓝色的部分会分成左右两部分,
  9. //hello在左边,猫图片在右边
  10. <div className="greeting"><div className="greeting-left"><img
  11. src="http://placekitten.com/g/64/64" />
  12. <div className="greeting-left-left">hello</div>
  13. <p>{this.state.date.toLocaleString()}</p></div> <div className="greeting-right">
  14. <p>hi</p> </div> </div>);}}
  15. ReactDOM.render( <Clock />,document.getElementById('root'));

执行结果
image.png

多层div的组合

  1. class Clock extends React.Component {
  2. constructor(props) {super(props);
  3. this.state = {date: new Date()};}
  4. //当删除componentWillunmount函数或者函数内不写方法的时候的时候,函数处于安装状态,时间会实时更新。
  5. //当删除componentDidmount函数或者函数内不写方法的时候,函数处于卸载状态,实时更新没有意义,
  6. //时间会停在某个时刻。
  7. //注意不能删除tick函数,否则安装和卸载函数都不能调用时间,该时间没有意义,不会实时刷新,会停在某个时刻。
  8. // 安装和删除函数都显示的时候,默认调用安装函数。
  9. componentDidMount() { this.timerID = setInterval(() => this.tick(),1000);}
  10. componentWillUnmount() { clearInterval(this.timerID);}
  11. tick() {this.setState({date: new Date()});}
  12. render() {
  13. return (<div><h2>It is {this.state.date.toLocaleTimeString()}.</h2></div>);}}
  14. //<p>{this.state.date.toLocaleString()}</p>
  15. function Comment(props){const date = new Date();
  16. return(
  17. //如果 hello的 greeting-left-left写成greeting-left,蓝色的部分会分成左右两部分,
  18. //hello在左边,猫图片在右边
  19. /date.toLocaleString()加不加 +“”都可以,在 const date后,这个已经是字符串
  20. <div className="greeting"><div className="greeting-left"><img
  21. src="http://placekitten.com/g/64/64"/>
  22. <div className="greeting-left-left">hello</div> <p>{date.toLocaleString()+""}</p>
  23. </div> <div className="greeting-right">hi</div></div>);}
  24. ReactDOM.render(<Comment />, document.getElementById('root'));

注意

class是 通过组件的渲染来实现 时间的实时更新的,function函数没有组件的方法,所以实时更新不能通过第二个案例来实现。