zoukankan      html  css  js  c++  java
  • 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';
    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 首先会比较元素内容先后的不同,而在渲染过程中只会更新改变了的部分。

  • 相关阅读:
    CSS3 transform 属性(2D,3D旋转)
    django中视图函数中装饰器
    第55课 经典问题解析四
    第52课 C++中的抽象类和接口
    机器学习中的数学(5)-强大的矩阵奇异值分解(SVD)及其应用
    对称矩阵、Hermite矩阵、正交矩阵、酉矩阵、奇异矩阵、正规矩阵、幂等矩阵、合同矩阵、正定矩阵
    机器学习算法之决策树
    python读写csv时中文乱码问题解决办法
    shiro工作过程
    Nginx在windows上安装 及 Nginx的配置及优化
  • 原文地址:https://www.cnblogs.com/chenyingying0/p/12690724.html
Copyright © 2011-2022 走看看