Passing props into external stylesheet in React Native?

后端 未结 4 1367
臣服心动
臣服心动 2020-12-16 14:08

I\'m new to React and React Native. At the moment for each component I\'m breaking the code into 2 separate files:

  1. index.js for all the React cod
相关标签:
4条回答
  • 2020-12-16 14:09

    Just wrap stylesheet in a function where you can optionally pass props.

    Instead of:

    const styles = StyleSheet.create({
      Title: { color: 'white' }
    });
    

    You do:

    const styles = (props?: any) => StyleSheet.create({
      Title: { color: 'white' }
    });
    

    And now when you add them to your components, instead of

    style={styles.Title}
    

    You do:

    style={styles(propsObjectHere).Title}
    

    and since this is optional and you have no props to pass, just do:

    style={styles().Title}
    

    P.S. ignore the type if you, for some reason, are not using TypeScript :P

    0 讨论(0)
  • 2020-12-16 14:30

    i'm sending noFooter boolean prop in a style sheet

       <View style={styles.mainFooterCont(noFooter)}>
         <Text> Testing </Text>
        </View>
    

    and receiving it like

      mainFooterCont: noFooter => ({
       flexDirection: 'row',
       justifyContent: 'space-between',
       alignItems: 'flex-end',
       paddingBottom: noFooter ? 0 : 20,
       paddingTop: Metrics.ratio(noFooter ? 0 : 5),
       }),
    
    0 讨论(0)
  • 2020-12-16 14:33

    Create a class that takes iconColor and iconSize as arguments and returns a StyleSheet object

    // styles.js
    
    export default class StyleSheetFactory {
        static getSheet(iconSize, iconColor) {
            return StyleSheet.create({
                icon : {
                    color: iconColor,
                    fontSize: iconSize
                }
            })
        }
    }
    
    // index.js
    
    render() {
        let myStyleSheet = StyleSheetFactory.getSheet(64, 'red')
    }
    
    0 讨论(0)
  • 2020-12-16 14:34

    I rather to have my styles in a separate file styles.js. Inside styles.js:

    export const styles = (props) => StyleSheet.create({
            icon : {
            color: props.iconColor,
            fontSize: props.iconSize
          }
        }
    

    Inside your main class you can pass the value

    return (
        <Icon style={styles(this.props).icon} />
      );
    

    Alternatively you can those value directly so it would be

    export const styles = (iconColor,iconSize) => StyleSheet.create({
        icon : {
        color: iconColor,
        fontSize: iconSize
      }
    }
    

    and inside your main class

    return (
        <Icon style={styles(this.props,iconColor, 
    this.props.iconSize).icon} />
     );
    
    0 讨论(0)
提交回复
热议问题