React 元素渲染简单演示

前端之家收集整理的这篇文章主要介绍了React 元素渲染简单演示前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

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 首先会比较元素内容先后的不同,而在渲染过程中只会更新改变了的部分。

原文链接:/react/881415.html

猜你在找的React相关文章