Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
542 views
in Technique[技术] by (71.8m points)

javascript - Passing props into external stylesheet in React Native?

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 code, and;
  2. styles.js for the StyleSheet

Is there a way to pass props into the external StyleSheet?

Example: index.js:

render() {
  const iconColor = this.props.color || '#000';
  const iconSize = this.props.size || 25;

  return (
    <Icon style={styles.icon} />
  );
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.8k users

...