zoukankan      html  css  js  c++  java
  • react入门(一):JSX渲染原理

    一.原理

    JSX的渲染原理主要分为三部分:

    1.基于babel-preset-react-app这个语法解析包,把jsx语法转换成一个名为 React.createElement() 的方法调用。

    const element = (
      <h1 className="greeting">
        Hello, world!
      </h1>
    );
    转换后为:
    const element = React.createElement(
      'h1',
      {className: 'greeting'},
      'Hello, world!'
    );
    <div>
        <h1 style='color: red' className='title'>todo with react</h1>
        <ul>
          <li>a</li>
          <li>b</li>
        </ul>    
    </div>
    转换后为:
    React.createElement("div", null, 
        React.createElement(
        "h1",
        { style: "color: red", className: "title"   },
        "todo with react"
       ), React.createElement("ul", null, React.createElement("li", null, "a"),
         React.createElement("li", null, "b") ) );

     2.基于createElement把传递的参数处理为jsx对象

    createElement():React在渲染解析的时候,会把所有的html标签都转换为(返回一个对象):
    返回对象的格式:
    {
      type: 'div'   ---存储的是标签名或者组件名
      props: {    ---props: 属性对象(给当前元素设置的属性都在这里)(如果有子元素,会多一个children属性,依次把子元素传递进来,没有就没有children属性)
        style: '',
        className: '',
        children: [] 可能有可能没有,有的话:可能是一个数组,也可能是一个字符串或者是一个对象。
      },
      key: null,
      ref: null
    }
    例如上面的jsx语法会返回:
    const element = {
      type: 'h1',
      props: {
        className: 'greeting',
        children: 'Hello, world'
      }
    };

    3.基于render把jsx对象按照动态创建dom元素的方式插入到指定的容器中即可。

     关于render函数

    render(jsx,container,callback)

    render(<h1>标题</h1>, document.getElementById('root'));

    主要接受三个参数:
    - jsx:javascript xml(html) react独有的语法;虚拟DOM(virtual dom)
    - container:虚拟DOM最后渲染到的容器,不建议是body
    - callback:把虚拟DOM插入到页面中,触发的回调函数(已经成为真实的DOM)

    2.语法

    具体实战代码

    index.js
    
    import React from 'react';
    import ReactDOM from 'react-dom';
    import App from './App';
    
    ReactDOM.render(<App />, document.getElementById('root'));
    

    App.js import React from 'react'; function App() { return (     //jsx语法:允许在js代码中直接写入html标签,并且可以在html标签中写入js表达式。     <div>       {2 + 1},hello react     </div>   ); }

    布尔值、Null 和 Undefined 被忽略:

    falsenullundefined 和 true 都是有效的子代,但它们不会直接被渲染。

    这些都是等价的

    <div></div> <div>{false}</div> <div>{null}</div> <div>{undefined}</div> <div>{true}</div>
    <div>
      {showHeader && <Header />}  //该JSX只会在showHeadertrue时渲染<Header />组件。
      <Content />
    </div>
  • 相关阅读:
    美国队长
    weka数据预处理
    weka特征选择(IG、chi-square)
    生成arff文件,csv转为arff
    logistic regression的一些问题,不平衡数据,时间序列,求解惑
    Feature Scaling
    【转】机器学习问题方法总结
    Canopy算法聚类
    ROC曲线及AUC评价指标
    评估指标:准确率(Precision)、召回率(Recall)以及F值(F-Measure)
  • 原文地址:https://www.cnblogs.com/chaixiaozhi/p/12161613.html
Copyright © 2011-2022 走看看