我将颜色作为 props.color 导入到我的功能组件中,并将其设置为状态“tagColor”。当我在样式表中使用 tagColor 作为值来设置背景颜色时,我收到错误“找不到变量 tagColor”
如何在样式表中使用变量?
const Tag = (props) => {
const [tagColor, setColor] = useState(props.color)
return (
<View style={styles.container}>
<TouchableOpacity style={styles.tag} title='tag'>
</TouchableOpacity>
</View>
);
}
const styles = StyleSheet.create({
container: {
alignItems: "center",
justifyContent: "center",
height: 25,
display: 'flex'
},
tag: {
backgroundColor: tagColor,
}
});
export default Tag;
嗯,它当然不认识tagColor
,它属于不同的范围。注意tagColor
是在你的函数组件的范围内,而StyleSheet
是不同的范围。
解决这个问题的一种方法是直接传递backgroundColor
to the style
道具,像这样:
<TouchableOpacity style={{backgroundColor: tagColor}} title="tag">
另一种方法是定义tag
你的班级StyleSheet
作为接收颜色并返回样式的函数,例如:
const styles = StyleSheet.create({
container: {
...
},
tag: tagColor => ({
backgroundColor: tagColor,
})
});
然后像这样使用它:
<TouchableOpacity style={styles.tag(tagColor)} title="tag">
如果你没有其他风格,我会选择第一种方式backgroundColor
。如果您需要更多样式,请使用第二种方法。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)