简体   繁体   中英

How To Pass Style Props into a reusable component in React Native for more flexible styling in the future

The Goal: To create a reusable react component and have the flexibility to style any part of the component in the future.

for example, I create a button-like component that I want to reuse in different cases in the future and give it different styles in the different places that I use it:

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'}
})

Question is: How do I make changes to the default styles in the future when I use this button?

The Goal: To create a reusable react component and have the flexibility to style any part of the component in the future.

How to achieve this:

  1. Create the reusable component using const or function.
  2. Pass 'props' as a parameter to the component, whether functional or const.
  3. Give the elements of your reusable component stylings that are arrays of the default styling and "props.futureStyle". Note that "futureStyle" here is just a name and you can use any name you want.
  4. Whenever you call the reusable component, you can easily use "futureStyle" to make any changes. Note that you can declare "futureStyle1", "futureStyle2" etc to the different parts of the reusable components so that you can edit the styles of every View, Text, etc that is part of the components wherever they may be added in the future

Example: Creating the reusable components:

 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,
 },
})

Henceforth, anywhere I wish to call and use the ReusableButton, it can edit the styles with the future styles. Example:

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>
)
}  

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM