在React Native中将道具传递到外部样式表中? [英] Passing props into external stylesheet in React Native?
本文介绍了在React Native中将道具传递到外部样式表中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我是React和React Native的新手.目前,对于每个组件,我都将代码分为2个单独的文件:
I'm new to React and React Native. At the moment for each component I'm breaking the code into 2 separate files:
-
index.js
用于所有React代码,以及; -
styles.js
用于StyleSheet
index.js
for all the React code, and;styles.js
for the StyleSheet
是否可以将道具传递到外部StyleSheet中?
示例:
index.js
:
render() {
const iconColor = this.props.color || '#000';
const iconSize = this.props.size || 25;
return (
<Icon style={styles.icon} />
);
}
示例styles.js
:
const styles = StyleSheet.create({
icon : {
color: iconColor,
fontSize: iconSize
}
});
上面的代码不起作用,但更多的地方只是为了使我明白我想做的事情.任何帮助深表感谢!
The code above does not work, but it's more there just to get the point across of what I'm trying to do. Any help is much appreciated!
推荐答案
创建一个将iconColor和iconSize作为参数并返回StyleSheet对象的类
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')
}
这篇关于在React Native中将道具传递到外部样式表中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文