詳解react實現(xiàn)插槽slot功能
背景
在開發(fā)一個需求時,需要對原來的 form 表單組件代碼復(fù)用并進行拓展。
場景A 使用原來的 form 表單組件。
場景B 在原來的表單組件基礎(chǔ)上,新增一些表單項,新增表單項位置動態(tài)插入在原來的表單組件中,位置隨意。
需求
復(fù)用表單組件,同時支持新增表單項。
解決方案
在 React 中,組件擴展和定制的能力,可以通過 props.children 和 render props 來實現(xiàn)。
以上兩種方式的缺點是:如果插入位置比較分散,需要定義children對象或多個 props,代碼繁瑣,不易維護。調(diào)研下來,目前貌似沒其他好的方法... 歡迎補充
props.children
props.children 直接將內(nèi)容作為一個HTML內(nèi)嵌結(jié)構(gòu)編寫,將組件參數(shù)與內(nèi)嵌結(jié)構(gòu)分開寫。
children 可以是一個字符串, 數(shù)組,對象等類型。可以使用 React.Children 的方法來判斷props.children 類型并處理。
function Father() {
return (
<div>
我是父組件Father
<Form1>
<div>我是子組件Form1的children</div>
</Form1>
<Form2>
{{
title: (<div>我是子組件Form2的title</div>),
content: (<div>我是子組件Form2的content</div>)
}}
</Form2>
</div>
)
}
function Form1(props) {
return (
<div>
我是子組件Form1
{props.children}
</div>
)
}
function Form2(props) {
return (
<div>
我是子組件Form2
{props.children.title}
{props.children.content}
</div>
)
}
render props
通過 props 參數(shù)傳入 JSX 元素的方法渲染,告知組件需要渲染什么內(nèi)容的函數(shù) prop??梢远x多個 props 參數(shù),不同位置渲染不同的 props。
function Father() {
return (
<div>
我是父組件Father
<Form1
children={<div>我是子組件Form1的children</div>}
/>
<Form2
title={<div>我是子組件Form2的title</div>}
content={<div>我是子組件Form2的content</div>}
/>
</div>
)
}
function Form1(props) {
return (
<div>
我是子組件Form1
{props.children}
</div>
)
}
function Form2(props) {
return (
<div>
我是子組件Form2
{props.title}
{props.content}
</div>
)
}
dataset
React 沒有專門的插槽,根據(jù) children/props 的特性,加上只讀屬性 dataset 實現(xiàn)一個類似的插槽功能。
非必要不使用,代碼會更加繁瑣。
如果有條件判斷是否展示,可以靈活設(shè)置 dataset 值使用。
function Father() {
return (
<div>
我是父組件Father
<Form1
type='text1'
title={<div>我是子組件Form的title</div>}
bottom={<div>我是子組件Form的bottom</div>}
>
<div data-type='text1'>
<label>性別:</label>
<input type="text" name="gender" />
</div>
<div data-type='text1,text2'>
<label>身高:</label>
<input type="text" name="height" />
</div>
<div data-type='text2,text3'>
<label>體重:</label>
<input type="text" name="weight" />
</div>
</Form1>
</div>
)
到此這篇關(guān)于詳解react實現(xiàn)插槽slot功能的文章就介紹到這了,更多相關(guān)react插槽slot內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
React State狀態(tài)與生命周期的實現(xiàn)方法
這篇文章主要介紹了React State狀態(tài)與生命周期的實現(xiàn)方法,本文給大家介紹的非常詳細,對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2021-03-03
react如何同步獲取useState的最新狀態(tài)值
這篇文章主要介紹了react如何同步獲取useState的最新狀態(tài)值問題,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2024-01-01
React庫之react-beautiful-dnd介紹及其使用過程
在使用React構(gòu)建Web應(yīng)用程序時,拖拽功能是一項常見需求,為了方便實現(xiàn)拖拽功能,我們可以借助第三方庫react-beautiful-dnd,本文將介紹react-beautiful-dnd的基本概念,并結(jié)合實際的項目代碼一步步詳細介紹其使用過程,需要的朋友可以參考下2023-11-11

