react更新元素渲染:计时器案例
src/index.js
import React from 'react'; import ReactDOM from 'react-dom'; import './index.css'; import App from './App'; import * as serviceWorker from './serviceWorker'; function tick(){ const element=( <div>现在是{new Date().toLocaleTimeString()}</div> ) ReactDOM.render( element,document.getElementById('example') ); } setInterval(tick,1000); // If you want your app to work offline and load faster,you can change // unregister() to register() below. Note this comes with some pitfalls. Learn more about service workers: https://bit.ly/CRA-PWA serviceWorker.unregister();
import React from 'react' Clock(props){ return( <div>现在是{props.date.toLocaleTimeString()}</div> ) } tick(){ ReactDOM.render( <Clock date={new Date()}/>,document.getElementById('example') ); } setInterval(tick,1)"> Learn more about service workers: https://bit.ly/CRA-PWA serviceWorker.unregister();
也可以改为类封装
import React,{ Component } from 'react'; class Clock extends React.Component { render(){ ( <div>现在是{this.props.date.toLocaleTimeString()}</div> ) } } Learn more about service workers: https://bit.ly/CRA-PWA serviceWorker.unregister();
React 只会更新必要的部分
值得注意的是 React DOM 首先会比较元素内容先后的不同,而在渲染过程中只会更新改变了的部分。