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'; import ReactDOM from 'react-dom'; import './index.css'; import App from './App'; import * as serviceWorker from './serviceWorker'; function Clock(props){ return( <div>现在是{props.date.toLocaleTimeString()}</div> ) } function tick(){ ReactDOM.render( <Clock date={new Date()}/>, 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, { Component } from 'react'; import ReactDOM from 'react-dom'; import './index.css'; import App from './App'; import * as serviceWorker from './serviceWorker'; class Clock extends React.Component { render(){ return( <div>现在是{this.props.date.toLocaleTimeString()}</div> ) } } function tick(){ ReactDOM.render( <Clock date={new Date()}/>, 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();
React 只会更新必要的部分
值得注意的是 React DOM 首先会比较元素内容先后的不同,而在渲染过程中只会更新改变了的部分。