React as a UI Runtime(二、React元素和入口)

发布时间:2019-06-24 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了React as a UI Runtime(二、React元素和入口)脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。

1、React元素

在宿主环境中,一个宿主实例是最小的单位(像DOM节点)。在React中最小的单位是React元素。
一个React元素就是一个描述宿主实例的Javascript对象。

// 用JSX语法糖对这个对象描述
// <button className="blue" />
{
  type: 'button',
  props: { className: 'blue' }
}

一个React元素没有宿主实例与它绑定,他只是描述你想在屏幕上看到的UI的描述,所以他是轻量级的。
就如同宿主实例,React也能实现树结构

// 用JSX语法糖对这些对象描述
// <dialog>
//   <button className="blue" />
//   <button className="red" />
// </dialog>
{
  type: 'dialog',
  props: {
    children: [{
      type: 'button',
      props: { className: 'blue' }
    }, {
      type: 'button',
      props: { className: 'red' }
    }]
  }
}

(提示:我忽视了一些对解释这个概念并不重要的属性)

但是,请记住React元素没有一致性的标记。他们总是不断的重建和销毁。
React元素是不可变的。比如,你不能改变一个React元素的children属性和其他属性。如果你想渲染与之前不同的内容,你要重头开始描述一个新的React元素。
我喜欢把React元素比做电影中的每一帧。它们描述了UI在某一刻的状态,它们永远不会改变。

2. 入口

每一个React渲染器都有一个入口。就是那个告诉React把特定的React元素树渲染到宿主实例中的API

ReactDOM.render(
  // { type: 'button', props: { className: 'blue' } }
  <button className="blue" />,
  document.getElementById('container')
);

当我们说ReactDOM.render(reactElement, domContainer),就意味着:“亲爱的React,将我的React元素放到domContainer 的宿主树去”。
React会看着reactElement.type(在我们的例子中,‘button’)并告诉React Dom renderer 创造一个宿主实例并且设置属性:

function createHostInstance(reactElement) {
  let domNode = document.createElement(reactElement.type);
  domNode.className = reactElement.props.className;
  return domNode;
}

在我们的例子中,代码如下

let domNode = document.createElement('button');
domNode.className = 'blue';

domContainer.appendChild(domNode);

如果 React 元素在 reactElement.props.children 中含有子元素,React 会在第一次渲染中递归地为它们创建宿主实例。

脚本宝典总结

以上是脚本宝典为你收集整理的React as a UI Runtime(二、React元素和入口)全部内容,希望文章能够帮你解决React as a UI Runtime(二、React元素和入口)所遇到的问题。

如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。