經(jīng)測試,由于微信小程序的 無法在循環(huán)中使用,因此 Children 和組合在微信小程序中也無法在循環(huán)中使用。百度小程序、支付寶小程序、H5、React Native 都可以在循環(huán)中使用此功能。
在我們設(shè)計組件時,有些組件通常不知道自己的子組件會有什么內(nèi)容,例如 Sidebar 和 Dialog 這樣的容器組件。
我們建議在這樣的情況使用 this.props.children 來傳遞子元素:
class Dialog extends Component {
render () {
return (
<View className='dialog'>
<View className='header'>Welcome!</View>
<View className='body'>
{this.props.children}
</View>
<View className='footer'>-- divider --</View>
</View>
)
}
}
這樣就能允許其它組件在 JSX 中嵌套任意子組件傳遞給 Dialog:
class App extends Component {
render () {
return (
<View className='container'>
<Dialog>
<View className="dialog-message">
Thank you for using Taro.
</View>
</Dialog>
</View>
)
}
}
在 <Dialog /> JSX 標(biāo)簽內(nèi)的任何內(nèi)容都會作為它的子元素(Children)都會傳遞到它的組件。
請不要對 this.props.children 進(jìn)行任何操作。Taro 在小程序中實現(xiàn)這個功能使用的是小程序的 slot 功能,也就是說你可以把 this.props.children 理解為 slot 的語法糖,this.props.children 在 Taro 中并不是 React 的 ReactElement 對象,因此形如 this.props.children && this.props.children、this.props.children[0] 在 Taro 中都是非法的。
this.props.children 無法用 defaultProps 設(shè)置默認(rèn)內(nèi)容。由于小程序的限制,Taro 也無法知道組件的消費者是否傳入內(nèi)容,所以無法應(yīng)用默認(rèn)內(nèi)容。
不能把 this.props.children 分解為變量再使用。由于普通的 props 有一個確切的值,所以當(dāng)你把它們分解為變量運行時可以處理,this.props.children 則不能這樣操作,你必須顯性地把 this.props.children 全部都寫完整才能實現(xiàn)它的功能。
自 1.1.9 開始支持
有些情況你不僅僅需要只傳遞一個子組件,可能會需要很多個「占位符」。例如在這個 Dialog 組件中,你不僅需要自定義它的 body,你希望它的 header 和 footer 都是給 Dialog 組件的使用者自由定制。這種情況可以這樣做:
class Dialog extends Component {
render () {
return (
<View className='dialog'>
<View className='header'>
{this.props.renderHeader}
</View>
<View className='body'>
{this.props.children}
</View>
<View className='footer'>
{this.props.renderFooter}
</View>
</View>
)
}
}
class App extends Component {
render () {
return (
<View className='container'>
<Dialog
renderHeader={
<View className='welcome-message'>Welcome!</View>
}
renderFooter={
<Button className='close'>Close</Button>
}
>
<View className="dialog-message">
Thank you for using Taro.
</View>
</Dialog>
</View>
)
}
}
在我們聲明 Dialog 組件時,header 和 footer 部分我們分別增加了 this.props.renderHeader 和 this.props.renderFooter 作為占位符。相應(yīng)地,我們在使用 Dialog 組件時,就可以給 renderHeader 和 renderFooter 傳入 JSX 元素,這兩個分別傳入的 JSX 元素將會填充它們在 Dialog 組件中的位置——就像在 Dialog JSX 標(biāo)簽里寫入的內(nèi)容,會填充到 this.props.children 的位置一樣。
組件的組合需要遵守 this.props.children 的所有規(guī)則。組合這個功能和 this.props.children 一樣是通過 slot 實現(xiàn)的,也就是說 this.props.children 的限制對于組件組合也都同樣適用。
所有組合都必須用 render 開頭,且遵守駝峰式命名法。和我們的事件規(guī)范以 on 開頭一樣,組件組合使用 render 開頭。
組合只能傳入單個 JSX 元素,不能傳入其它任何類型。當(dāng)你需要進(jìn)行一些條件判斷或復(fù)雜邏輯操作的時候,可以使用一個 Block 元素包裹住,然后在 Block 元素的里面填充其它復(fù)雜的邏輯。
更多建議: