React

React(update the UI的三种方法)

2017-10-22  本文已影响5人  余生筑

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

function tick() {
  const element = (
    <div>
      <h1>Hello, world!</h1>
      <h2>It is {new Date().toLocaleTimeString()}.</h2>
    </div>
  );
  ReactDOM.render(
    element,
    document.getElementById('root')
  );
}

setInterval(tick, 1000);

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

function Clock(props) {
  return (
    <div>
      <h1>Hello, world!</h1>
      <h2>It is {props.date.toLocaleTimeString()}.</h2>
    </div>
  );
}

function tick() {
  ReactDOM.render(
    <Clock date={new Date()} />,
    document.getElementById('root')
  );
}

setInterval(tick, 1000);

缺陷: <Clock date={new Date()} />的形式不够严密,我们希望Clock组件不向外暴露任何和时间状态有关的接口。

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 (
      <div>
        <h1>Hello, world!</h1>
        <h2>It is {this.state.date.toLocaleTimeString()}.</h2>
      </div>
    );
  }
}

ReactDOM.render(
  <Clock />,
  document.getElementById('root')
);
上一篇下一篇

猜你喜欢

热点阅读