我想在
StyleSheet.create
的参数对象中重用样式,该怎么做?
看代码:
const styles = StyleSheet.create({
style1: {
color: "red",
backgroundColor: "white"
},
style2: {
width: 100,
...style1
}
})
最初,我希望
style2
从 color
继承所有 backgroundColor
和 style1
,并再扩展 1 个名为 width
的属性。所以我尝试了上面的代码,但随后出现错误“style1 未声明”。
我意识到了问题所在,所以我将 ...style1
替换为 ...this.style1
,错误消失了,但它没有按照我的预期工作。我想知道为什么,并尝试在 javascript 中运行此代码片段来测试行为:
styles = {
style1: {
color: "red",
backgroundColor: "white"
},
style2: {
width: 100,
inherit: this.style1
}
}
console.log(styles.style2.inherit)
它拉出了结果
undefined
,这不是styles.style1
。我再次意识到这个问题,在用 inherit: this.style1
替换 inherit: styles.style1
后,javascript 片段 可以工作,但在 React Native 代码中不。
我想到目前为止,你已经明白我想要什么了,所以我的问题是如何实现这一目标(在 React Native 中重用样式代码)?我认为会有很多解决方法,所以请尽可能多地给我。谢谢你。
这是我尝试过但没有得到预期结果的语法列表(或者因为我的大脑不能正常工作,所以我错了):
...style1
...this.style1
...styles.style1
...StyleSheet.style1
...StyleSheet.flatten(styles.style1)
const baseStyle = {
color: 'red',
backgroundColor: 'white'
}
const styles = StyleSheet.create({
style1: baseStyle,
style2: {
width: 100,
...baseStyle
}
})
解决方案2 使用
Styled Components轻松管理和重用样式。
style1
对象放在
StyleSheet.create
之外:
const style1 = {
color: "red",
backgroundColor: "white"
}
const styles = StyleSheet.create({
style2: {
width: 100,
...style1
}
})
有更好的方法吗?因为
style1
也可以是另一个元素使用的样式,所以我不能再使用
<Element style={styles.style1}/>
了...
const baseStyles = StyleSheet.create({
container: {
borderWidth: 1,
borderRadius: 10,
flex: 1,
},
});
export const styles = StyleSheet.create({
container: baseStyles.container,
card: {
backgroundColor: "lightblue",
...baseStyles.container,
},
});