我們通常封裝組件,會看到使用{...props}來傳遞子組件B從父組件A接收到的屬性給孫子組件C(剩餘父組件屬性傳遞給孫子組件的屬性),那麼,是否意味着只要子組件{...props}後,子組件就可以直接使用該屬性呢?
答案是否定的,{...props}只能在當前組件沒有用到時,將子組件從父組件接收到的屬性傳遞給孫子組件,如果直接使用未定義的屬性,則會報錯!
// 父組件A
<Tabs
searchType
tabs={list}
tabBarHeight={OASize(45)}
swipeable={false}
keyExtractor={(item, index) => index + ""}
onChange={() => {}}
initialPage={currKey}
// page={'0'}
showUnderline={true}
tabBarTextStyle={{ fontSize: OASize(14) }}
tabBarActiveTextStyle={{ fontSize: OASize(20), fontWeight: "bold" }}
tabBarActiveTextColor={OAColor.headBg}
tabBarBackgroundColor={OAColor.white}
renderContent={(tab, index) => {
return <View style={{ flex: 1 }}>{this.renderTab(tab.title)}</View>;
}}
tabBarInactiveTextColor={OAColor.lightText}
tabBarUnderlineStyle={{
backgroundColor: OAColor.headBg,
width: "35%",
height: OASize(2),
marginBottom: 5
}}
/>
// 子組件B
<AntTabs
tabs={tabs}
initialPage={initialPage}
tabBarPosition="top"
renderTabBar={props =>
firstLoading != null ? (
firstLoading === false ? (
<TabBar
tabBarHeight={tabBarHeight}
keyExtractor={keyExtractor}
renderUnderline={renderUnderline}
customUnderLine={customUnderLine}
tabRef={tabRef}
doubleClickFn={doubleClickFn}
renderTab={props => (
<TabItem
{...props}
tabBarActiveTextColor={tabBarActiveTextColor}
tabBarActiveTextStyle={tabBarActiveTextStyle}
tabBarTextStyle={tabBarTextStyle}
/>
)}
{...props}
{..._props}
/>
) : null
) : (
<TabBar
tabBarHeight={tabBarHeight}
keyExtractor={keyExtractor}
renderUnderline={renderUnderline}
customUnderLine={customUnderLine}
tabRef={tabRef}
doubleClickFn={doubleClickFn}
renderTab={props => (
<TabItem
{...props}
tabBarActiveTextColor={tabBarActiveTextColor}
tabBarActiveTextStyle={tabBarActiveTextStyle}
tabBarTextStyle={tabBarTextStyle}
/>
)}
{...props}
{..._props}
/>
)
}
{..._props}
>
{renderContent}
</AntTabs>
// 孫子組件C
render() {
const {
style,
title,
active,
badge,
tabBarTextStyle,
tabBarActiveTextColor,
tabBarActiveTextStyle
} = this.props;
console.log("tabBarActiveTextStyle:", tabBarActiveTextStyle);
return (
<View style={[styles.container, active && styles.activeContainer, style]}>
<Text
style={[
styles.title,
tabBarTextStyle,
active && styles.activetitle,
active && tabBarActiveTextColor && { color: tabBarActiveTextColor },
active && tabBarActiveTextStyle
]}
>
{title}
</Text>
{!active && !!badge && (
<BadgeView
style={[
styles.badge,
typeof badge === "number" && { top: 0, right: 0 },
badge === "dot" && title.length === 2 && { right: 10 }
]}
badgeSize={typeof badge === "number" ? 10 : 7}
badgeText={badge}
badgeBackgroundColor="#E1575C"
/>
)}
</View>
);
}