我在文本元素周圍創建了一個包裝器:
export type PoppinsTextProps = PropsWithChildren < TextProps>
export default function PoppinsText(props: PoppinsTextProps) {
return React. cloneElement(<Text {...props}. />, { style: styles.text }, props.children)。)
}
const styles = StyleSheet.create({
text: {
fontFamily: "Poppins-Medium"。
}
});
它按預期作業,例如:
<PoppinsText text20> Hello< /PoppinsText>
正如你所看到的,我可以在包裝器和文本上傳遞相同的屬性。
。問題是,你是否會像我一樣以同樣的方式包裝Text元素?
uj5u.com熱心網友回復:
不,我們不需要呼叫cloneElement來包裝一個組件,我們可以直接回傳帶有props的Text組件。
export default function PoppinsText(props。PoppinsTextProps) {
const {style, ...otherProps} = props
return <Text {...otherProps} 。style={StyleSheet.flatten([style, styles.text]})。/>
}
如果我們想接觸子代或輸入組件的道具,我們將使用cloneElement。
例如,有不同的容器所提供的不同的道具:
const ReverseContainer=()=> {
const newStyle = { color: "red" }。
const RenderChildren = (/span>) =>
React.Children.map(props. children, (child) =>/span> {
return React.cloneElement(child, {
style: StyleSheet.flatten([props.childrenStyle, newStyle])。
});
});
return <Card>/span>{< RenderChildren />}</Card>>。
};
BTW,也許你只是想定義你的預置。 https://wix.github.io/react-native-ui-lib/foundation/style
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/326342.html
標籤:
