我定义的颜色常量:
export const COLORS = {
red: '#E90716',
black: '#000000',
// other colors
}
在一个组件文件中,我导入它:
import {COLORS} from '../colors.js'
在组件中,我嵌套了Text
元素,我想在其中应用红色:
return (
<View>
<Text>
Blabla
<Text
style={styles.myText}>
I am red.
</Text>
</Text>
</View>
);
...
const styles = StyleSheet.create({
myText: {
color: COLORS.red,
},
});
但当我运行应用程序时,我出现了错误:
Invariant Violation: Invalid prop 'color' supplied to `StyleSheet myText`: E90716
为什么会出现这种错误?如何使用我定义为Text
元素常量的颜色代码?
=====更新======
但如果我改为使用硬编码的颜色代码,它是有效的。
例如
const styles = StyleSheet.create({
myText: {
color: 'red',
},
});
如果我不使用COLORS中的十六进制代码,例如,它也可以工作
// it works as well!
export const COLORS = {
red: 'red'
}
为什么?为什么我用十六进制值定义的颜色常量不起作用?
我刚刚用这段代码进行了测试,它可以正常工作,您可以检查链接expo链接。
我相信你在其他组件中使用了styles.myText,比如View之类的,因此颜色不是样式属性,因此出现了错误。一定要检查一次。
更新:
你把这些颜色和引号放在一起了吗?或者你没有报价:
export const COLORS = {
red: '#E90716',
}
或
export const COLORS = {
red: #E90716,
}
放心吧。希望它能帮助