React State(状态)

function FormattedDate(props){
  return (
    <h1>现在是{props.date}</h1>
  )
}
class Clock extends React.Component{
  constructor(props){
    supper(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>
        <FormattedDate date={this.state.date}/>
      </div>
    }
  }
}
function App(){
  return{
    <div>
      <Clock/>
      <Clock/>
    </div>
  }  
}
ReactDOm.render(<App/>,document.getElementById('example'))

猜你喜欢

转载自www.cnblogs.com/shui1993/p/9959155.html