[英]How To Pass Style Props into a reusable component in React Native for more flexible styling in the future
目標:創建一個可重用的 React 組件,並在未來靈活地為組件的任何部分設置樣式。
例如,我創建了一個類似按鈕的組件,我想在未來的不同情況下重用它,並在我使用它的不同地方賦予它不同的樣式:
function reusableButton(){
return(
<View style={styles.defaultStyle}>
<Text style={styles.defaultTitleStyle}>Button Title</Text>
</View>
)}
const styles = StyleSheet.create({
defaultStyle:{
height: 50,
width: 100,
borderRadious: 25,
backgroundColor:'red'},
defaultTitleStyle: {
color:'green',
fontWeight: 'bold'}
})
問題是:當我使用這個按鈕時,將來如何更改默認樣式?
目標:創建一個可重用的 React 組件,並在未來靈活地為組件的任何部分設置樣式。
如何實現這一點:
示例:創建可重用組件:
const ReusableButton = (props) =>{
return(
<View style={[styles.currentButtonStyle, props.futureButtonStyle]}>
<Text style={[styles.currentButtonTitle, props.futureTitleStyle]}>{props.title}</Text>
</View> )};
//Here are my default styles:
const styles = Stylesheet.create({
currentButtonStyle: {
height:50,
width: 100,
backgrroundColor:'red'},
currentButtonTitle:{
color: 'white'
fontSize: 20,
},
})
從此以后,在我希望調用和使用 ReusableButton 的任何地方,它都可以使用未來的樣式編輯樣式。 例子:
function NewComponent(){
return(
<View>
<Text>Hi let us make use of our old reusable button</Text>
<ReusableButton futureButtonStyle={{width: 200, height: 100, backgroundColor:'blue'}} futureTitleStyle={{fontWeight:'bold', fontSize: 50}}/>
</View>
)
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.