React Fragments 内部是如何工作的?
React 致力于保持简洁,所以才有了 fragments。它们可以在渲染多个元素时去除多余的包装器!
这非常酷,但它们在底层是如何工作的呢?
👉 React Fragment 只是一种特殊类型的 React Element!
JSX 是调用React.createElement
此函数的语法糖,仅需要三种可能的类型组:
- 基本 HTML 元素的标签名称
- 用户定义组件的类/函数
- React 片段类型
// what you write
const Items = () => {
return (
<>
<li>First element</li>
<li>Second element</li>
<li>Third element</li>
</>
);
}
// what React gets after babel transpilation
const Items = () => {
return React.createElement(
React.Fragment,
null,
React.createElement("li", null, "First element"),
React.createElement("li", null, "Second element"),
React.createElement("li", null, "Third element")
);
};
👉 React 如何处理片段?
毕竟没有对应的DOM元素!
React 不需要真实的 DOM 元素来处理 fragment。
它使用虚拟 DOM 来代替 💡
// Items() return this
{
"type": Symbol(react.fragment),
"key": null,
"ref": null,
"props": {
"children": [
{
"type": "li",
"key": null,
"ref": null,
"props": {
"children": "First element"
},
},
// ...
]
}
}
ReactDOM
反过来,忽略片段并呈现所有子项而没有任何包装器。
👉 亲自验证它是否有效!
转到reactjs.org并粘贴组件Items
。
如果 DOM 看起来和这里一样👇,那么你就做得很好!
<div id="___gatsby">
<li>First element</li>
<li>Second element</li>
<li>Third element</li>
</div>
PS:在 Twitter 上关注我,获取更多类似内容!
鏂囩珷鏉ユ簮锛�https://dev.to/fromaline/how-do-react-fragments-work-under-the-hood-36n5