React利用props的children實現(xiàn)插槽功能
可能會比較遺憾的說 React中并沒有vue中的 slot 插槽概念 不過 可以通過props.children 實現(xiàn)類似功能
我們先創(chuàng)建一個React項目
在src下創(chuàng)建目錄components 在下面創(chuàng)建一個dom.jsx組件
參考代碼如下
import React from "react"
export default class dom extends React.Component {
constructor(props){
super(props);
this.state = {
}
}
render(){
return (
<div>
<div>這里是dom組件</div>
<div>{ this.props.children }</div>
<div>元素結束</div>
</div>
)
}
}這里 大家可以將this.props.children 理解為我們vue中的slot父組件插入的內(nèi)容就會放在這個位置
我們 App根組件編寫代碼如下
import React from "react"
import Dom from "./components/dom"
export default class App extends React.Component {
constructor(props){
super(props);
this.state = {
}
}
render(){
return (
<div>
<Dom>
<div>這是插槽內(nèi)容</div>
</Dom>
</div>
)
}
}我們正常調(diào)用了剛才寫的dom組件 在中間插入了一個div 內(nèi)容為 這是插槽內(nèi)容
我們運行結果如下

可以看到 我們的內(nèi)容被成功插入在了 this.props.children 的位置
知識補充
可能有小伙伴對于props.children并不太熟悉,下面小編為大家整理了props.children的相關知識,希望對大家有所幫助
簡介
在典型的React數(shù)據(jù)流模型中,props 是組件對外的接口。props 作為父子組件溝通的橋梁,為組件的通信和傳值提供了重要手段。
this.props 對象的屬性與組件的屬性一一對應,但其中有一個比較特殊的參數(shù):this.props.children。它表示組件所有的子節(jié)點。
在組件內(nèi)部使用 this.props.children,可以拿到用戶在組件里面放置的內(nèi)容。
如下例,一個 span 標簽在 Parent 中作為Child的子節(jié)點傳入,可在 Child 中通過 this.props.children 取到:
class Parent extends React.Component {
render() {
return (
<Child>
<span>{'child node'}</span>
</Child>
);
}
}class Child extends React.Component {
render() {
return (
<div>
{this.props.children}
</div>
);
}
}React.Children 方法
React 提供了工具方法 React.Children 來處理 this.props.children。
1. React.Children.map
object React.Children.map(object children, function fn)
遍歷 props.children ,在每一個子節(jié)點上調(diào)用 fn 函數(shù)。
2. React.Children.forEach
React.Children.forEach(object children, function fn)
類似于 React.Children.map(),但是不返回對象。
3. React.Children.count
number React.Children.count(object children)
返回 children 當中的組件總數(shù)。
4. React.Children.only
object React.Children.only(object children)
返回 children 中僅有的子節(jié)點。如果在 props.children 傳入多個子節(jié)點,將會拋出異常。
到此這篇關于React利用props的children實現(xiàn)插槽功能的文章就介紹到這了,更多相關React插槽內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
react?fiber使用的關鍵特性及執(zhí)行階段詳解
這篇文章主要為大家介紹了react?fiber使用的關鍵特性及執(zhí)行階段詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2023-05-05
React內(nèi)部實現(xiàn)cache方法示例詳解
這篇文章主要為大家介紹了React內(nèi)部實現(xiàn)cache方法示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2022-11-11
react中的useImperativeHandle()和forwardRef()用法
這篇文章主要介紹了react中的useImperativeHandle()和forwardRef()用法,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-08-08
使用React實現(xiàn)一個簡單的待辦事項列表的示例代碼
這篇文章我們將詳細講解如何建立一個這樣簡單的列表,文章通過代碼示例介紹的非常詳細,對我們的學習或工作有一定的幫助,需要的朋友可以參考下2023-08-08

