将本机Javascript对象提供给React

我在以下链接中找到了有趣的片段:

https://facebook.github.io/react/blog/2015/12/18/react-components-elements-and-instances.html

本文描述了React如何在内部使用本机Javascript对象来构建树.
目前我正在开发一个拖放编辑器,我想为其构建一个React组件树.理想情况下,我会构建一个嵌套的Javascript对象树,并在运行时将它们转换为组件树.

例如,如果我有一个像这样的对象(添加了链接的片段):

{
  type: Button,
  props: {
    children: 'OK!',
    color: 'blue'
  }
}

这就是内部反应的计算方法.
如何立即将此对象(/对象树)提供给React?

我认为添加的代码片段是伪代码.以下例如不起作用:

ReactDOM.render({
  type: Button,
  props: {
    children: 'OK!',
    color: 'blue'
  }
}, document.getElementById('root'));

最佳答案 您需要添加一个额外的属性作为安全措施,以避免在JSON中注入组件(无法从JSON创建所需的符号).

它在foot note中解释:

All React elements require an additional $$typeof:
Symbol.for(‘react.element’) field declared on the object for security
reasons. It is omitted in the examples above. This blog entry uses
inline objects for elements to give you an idea of what’s happening
underneath but the code won’t run as is unless you either add $$typeof
to the elements, or change the code to use React.createElement() or
JSX.

const Button = ({ color, children }) => <button style={{ background: color }}>{children}</button>;

ReactDOM.render({
  $$typeof: Symbol.for('react.element'),
  type: Button,
  props: {
    children: 'OK!',
    color: 'blue'
  }
}, document.getElementById('root'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>

<div id="root"></div>
点赞