简体   繁体   中英

How do I pass a prop to a stylesheet in React Native?

I have a prop called isProfile which is used by a component (Feed) that uses the stylesheet below. I want to conditionally render the height of the container based on whether the isProfile prop is set as true or false.

function Feed({isProfile}){
    return(
      <View style={style.container}>
      </View>

)

}

    
const styles =  StyleSheet.create({
    container:{
       backgroundColor:colors.primary,                     
       width:windowWidth,
       justifyContent:"center",
       height: isProfile ? windowHeight : windowHeight*0.87,

    },

This is how I solved my problem.

I changed my styleSheet code as such

const styles = (isProfile) => StyleSheet.create({
container:{

   backgroundColor:colors.primary,           
   width:windowWidth,
   justifyContent:"center",
   height: isProfile ? windowHeight : windowHeight*0.87,

},
)}

And then I passed to prop to the styleSheet as such

        <View style={styles(isProfile).container}>
        </View>

You should change styles to a function that accepts the parameter:

function Feed({isProfile}){
    return(
      <View style={createStyles(isProfile).container}>
      </View>

)

}


const createStyles = (profile) => StyleSheet.create({
    container:{
       backgroundColor:colors.primary,                     
       width:windowWidth,
       justifyContent:"center",
       height: profile ? windowHeight : windowHeight*0.87,

    },

The isProfile variable (prop) is local to the component and invisible outside, so it must be passed as the parameter

You can store mutiple styles by using an array of objects for style style={[{},{}]} etc.. This allows you to add the second part I added

function Feed({isProfile}){
    return(
      <View style={[style.container,{height: isProfile ? windowHeight : windowHeight*0.87,}]}>
      </View>

)

}

    
const styles =  StyleSheet.create({
    container:{
       backgroundColor:colors.primary,                     
       width:windowWidth,
       justifyContent:"center",

    },

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