gpt4 book ai didi

javascript - 将原生 Javascript 对象提供给 React

转载 作者:塔克拉玛干 更新时间:2023-11-02 21:27:48 27 4
gpt4 key购买 nike

我在以下链接中找到了有趣的片段: 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 内部计算的。我如何立即将这个对象(/对象树)提供给 React?

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

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

最佳答案

您需要添加一个额外的属性作为安全措施,以避免在 JSON 中注入(inject)组件(不可能从 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>

关于javascript - 将原生 Javascript 对象提供给 React,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39078524/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com