React(update the UI的三种方法)

如何更新一个Clock组件的时间状态

  • 方法1:setInterval()
function tick() {
  const element = (
    

Hello, world!

It is {new Date().toLocaleTimeString()}.

); ReactDOM.render( element, document.getElementById('root') ); } setInterval(tick, 1000);

缺陷:没有把时间更新功能封装至Clock体内。

  • 方法2:利用props
function Clock(props) {
  return (
    

Hello, world!

It is {props.date.toLocaleTimeString()}.

); } function tick() { ReactDOM.render( , document.getElementById('root') ); } setInterval(tick, 1000);

缺陷: 的形式不够严密,我们希望Clock组件不向外暴露任何和时间状态有关的接口。

  • 方法3 利用state

components defined as classes have some additional features. Local state is exactly that: a feature available only to classes.

class Clock extends React.Component {
  constructor(props) {
    super(props);
    this.state = {date: new Date()};
  }

  render() {
    return (
      

Hello, world!

It is {this.state.date.toLocaleTimeString()}.

); } } ReactDOM.render( , document.getElementById('root') );

你可能感兴趣的:(React(update the UI的三种方法))