我想在 StyleSheet.create
的参数对象中重用样式,该怎么做?
查看代码:
const styles = StyleSheet.create({
style1: {
color: "red",
backgroundColor: "white"
},
style2: {
width: 100,
...style1
}
})
本来我想让style2
继承style1
的所有color
和backgroundColor
,再扩展1个属性称为宽度
。所以我确实尝试了上面的代码,但随后出现错误“style1 is not declared”。
我意识到了这个问题,所以我将 ...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)
最佳答案
不可能Self-references in object literals / initializers
解决方案:1
const baseStyle = {
color: 'red',
backgroundColor: 'white'
}
const styles = StyleSheet.create({
style1: baseStyle,
style2: {
width: 100,
...baseStyle
}
})
解决方案 2 使用 Styled Components轻松管理和重用样式。
关于javascript - 如何在 React Native 的 StyleSheet.create 中继承样式(可能使用解构语法),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58197241/