我使用 React 開發了幾個月,但沒有完全理解 React 元件模型的真正威力。有一天,我決定深入研究作曲,這就是我學到的東西。
在 React 中,一個元件可以有一個、多個子元件,也可以沒有子元件。很好,但是等等 —— 什麼是「孩子」?我們用一個例子來解釋:
Profile 元件有兩個子元件:ProfileImage 和 ProfileDetails,而這兩個元件沒有子元件.
「在同時包含開始標籤和結束標籤的 JSX 表達式中,這些標籤之間的內容會以特殊 props 傳遞:props.children」 — React 文件
本質上,props.children是一個特殊的prop,自動傳遞給每個元件,可用於在呼叫元件時渲染開始和結束標籤之間包含的內容。這些類型的元件被官方文件標識為“boxes”。
在 React 的 JSX 中,帶有子組件的元件始終由開始標籤和結束標籤標識。每個子項都必須放置在這兩個標籤之間,就像我們在上面看到的那樣。當元件沒有子元件時,您可以使用
假設我們要建立一個 ImageSlider 元件。我們的目標是像這樣呼叫元件:
可以看到,ImageSlider是由幾個組成的可以透過 props.children 存取和渲染。
感謝 props.children 我們可以將內容嵌套在組件中,就像嵌套常見的 HTML 元素一樣.
透過 props.children 傳遞給組件的內容可以包含
undefined、null、布林值、數字、字串、React 元素或任何這些類型的遞歸數組。它也可以是傳回這些類型之一的函數。
請注意,如 React 文件中所提到的, false、null、undefined 和 true 是有效的子元素,但它們將被忽略並且不會渲染。如果想要渲染 false、true、null 或 undefined,則必須先將其轉換為字串:
props.children 允許我們組合組件,從而組合我們的前端介面;利用 React 組件模型的真正力量。
「React 擁有強大的組合模型,我們建議使用組合而不是繼承來在元件之間重用程式碼。」 — React 文件
正如官方文件中所述,有時您可能需要填充組件中的多個「漏洞」。在這種情況下,定義多個自訂 props 可能是更好的方法,而不是使用 props.children;如下例所示:
「React.Children 提供了處理 props.children 不透明資料結構的實用程式」 — React 文件
為什麼 props.children 是一個「不透明的資料結構」?
因為 props.children 可以由一個、多個或沒有子元素組成,這意味著它的值可以是單個子節點,一組子節點,或者未定義分別。感謝 React.Children API,我們可以輕鬆處理 props.children,而無需考慮其每種可能的類型。值得慶幸的是,一切都會在後台為我們處理。
在撰寫本文時,React.Children 提供了五種不同的實用程式:
地圖
對於每個
數數
僅
到陣列
讓我們透過一個例子來看看如何使用 React.Children。假設我們想要將特殊的 CSS 類別 img-special-class 加入到 ImageSlider 元件的每個子元件中。這可以如下完成:
export default function ImageSlider(props) { const { children } = props return ({ React.Children.map(children, (child) => React.cloneElement(child, { className: `${child.props.className} img-special-class` }) ) }); }
React.Children.map allows us to iterate over props.children and transform each element according to the function passed as the second parameter. To achieve our goal, we used React.cloneElement. This is because we needed to change the value of the className prop, but props are immutable in React, so we had to clone each child.
Mastering props.children is essential to becoming a great React developer and beginning to harness the full potential of the React component model. props.children is one of React's most useful features, since it gives us the ability to render child components. Because of this, every developer should know how to use it properly.
I hope this article helps you master composition in React.
The post "A Complete Guide To props.children In React" appeared first on Writech.
以上是React 中 props.children 的完整指南的詳細內容。更多資訊請關注PHP中文網其他相關文章!