react 中文文档案例一 (倒计时)

 

1.函数试组件

import React from 'react';
import ReactDOM from 'react-dom';

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);

2.函数试组件改成类组件


import React from 'react';
import ReactDOM from 'react-dom';
class Clock extends React.Component {
    render() {
      return (
        <div>
          <h1>Hello, world!</h1>
          <h2>It is {this.props.date.toLocaleTimeString()}.</h2>
        </div>
      );
    }
  }
function tick() {
    ReactDOM.render(
        <Clock date={new Date()}/>,
        document.getElementById('root')
    );
}
  
  setInterval(tick, 1000);

 

import React from 'react';
import ReactDOM from 'react-dom';

function FormattedDate(props) {
    return <h2>It is {props.date.toLocaleTimeString()}.</h2>;
}
  
class Clock extends React.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 (
        <div>
          <h1>Hello, world!</h1>
          <FormattedDate date={this.state.date} />
        </div>
      );
    }
  }
  
class App extends React.Component {
    render(){
        return (
            <div>
              <Clock />
              <Clock />
              <Clock />
            </div>
          );
    }
}
ReactDOM.render(
    <App />,
    document.getElementById('root')
);

 

posted @ 2019-01-31 14:29  Lolita_web  阅读(376)  评论(0编辑  收藏  举报