在我的应用程序中,我将 DOM 序列化为 JSON 并将其发送回服务器。
我需要帮助找到一种有效的方法,以便稍后使用 React 从序列化的 JSON 中重建 DOM。
为了分享一个具体的示例,让我们从这个 DOM 开始:
<div id="parent">
<div id="one"></div>
<span id="two"></span>
</div>
这将被序列化为以下 JSON:
[
{
"index": 0,
"tagName": "DIV",
"attributes": {"id": "parent"}
},
{
"index": 1,
"parent": 0,
"tagName": "DIV",
"attributes": {"id": "one"}
},
{
"index": 2,
"parent": 0,
"tagName": "SPAN",
"attributes": {"id": "two"}
}
]
现在,在普通的 Javascript 中,我可以像下面这样重新构建 DOM:
var nodes = {};
for (var i = 0; i < json.length; i++) {
var node = json[i];
// Create element
var element = document.createElement(node.tagName);
// Add attributes
for (var attribute in node.attributes) {
element.setAttribute(attribute, node.attributes[attribute]);
}
// Add parent-child association
if (node.parent != undefined) nodes[node.parent].appendChild(element);
// Cache it for later reference
nodes[node.index] = element;
}
我是 React 新手,到目前为止,我还没有找到一种方法来建立组件之间的动态父子关系,以便以后可以更改。使用 React 来完成此任务的好方法是什么,或者可能是,它是 React 的一个很好的应用吗?
上面的示例是一个简化的示例,但您可以想象,随着引入不同的 JSON 指令来重新设置父级、添加或删除特定 DOM 节点,复杂性会增加。
最佳答案
如果您递归地反序列化 JSON,则无需显式管理父子关系。
将 JSON-HTML 表示形式提供为树(而不是列表),并确保序列化对所有标记遵守一致的模式 - 然后(至少在理论上)它们可以由同一个 React 组件进行解释。
下面有些详细说明,有两点需要注意
- 每个标签都需要一个唯一的 key ,例如哈希值或应用程序 ID
- 所有节点(尤其是纯文本节点)都需要 html 根(我选择了标签
<text>
以在<p>
和<div>
正文中启用纯文本内容
输出应该是
<div id="root_node">
<div>
<p><i>hi </i><b>there </b><text>friend</text></p>
<p><b>hey</b></p>
</div>
<p><i>hey again</i></p>
</div>
react 代码
class JsonToHtml extends React.Component {
constructor(props) {
super(props);
this.state = {
json_html:
{ node : 'root',
child: [
{ type: 'parent', tag: 'div', key: '84a4fb',
child: [
{ type: 'parent', tag: 'p', key: '1bb600',
child: [
{type: 'child', tag: 'i', val: 'hi ', key: 'f6a3ad'},
{type: 'child', tag: 'b', val: 'there ', key: '57ef5e'},
{type: 'child', tag: 'text', val: 'friend', key: '57ef52'}
]
},
{ type: 'parent', tag: 'p', key: 'a43a9f',
child: [
{type: 'child', tag: 'b', val: 'hey', key: '4e2d46'},
]
}
]
},
{ type: 'parent', tag: 'p', key: '3e21f6',
child: [
{type: 'child', tag: 'i', val: 'hey again', key: 'ed5a49'},
]
}
]
}
};
}
render() {
return (
<div id='root_node'>
{this.state.json_html.child.map(function(node) {
return (
<HtmlComponent key={node.key} node={node} />
)
})
}
</div>
)
}
} export default JsonToHtml
class HtmlComponent extends React.Component {
render() {
if (this.props.node.type == "child") {
return React.createElement(
this.props.node.tag, {},
this.props.node.val)
}
if (this.props.node.type == "parent") {
return React.createElement(
this.props.node.tag, {},
this.props.node.child.map(function(node) {
return (
<HtmlComponent key={node.key} node={node} />
)
})
)
}
}
}
关于javascript - 如何使用 React 重构 JSON 中的序列化 DOM?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38957639/