Huỳ*_*yễn 2 javascript ecmascript-6 react-native react-native-stylesheet
我想在StyleSheet.create的参数对象中重用样式,该怎么做?
看代码:
const styles = StyleSheet.create({
style1: {
color: "red",
backgroundColor: "white"
},
style2: {
width: 100,
...style1
}
})
Run Code Online (Sandbox Code Playgroud)
最初,我想style2继承 allcolor和backgroundColorfrom style1,并扩展 1 个名为width. 所以我确实尝试了上面的代码,但是它得到了一个错误“style1 未声明”。我意识到了这个问题,所以我替换...style1为...this.style1,错误消失了,但它没有按我预期的那样工作。我想知道为什么并尝试在 javascript 中运行此代码段来测试行为:
const styles = StyleSheet.create({
style1: {
color: "red",
backgroundColor: "white"
},
style2: {
width: 100,
...style1
}
})
Run Code Online (Sandbox Code Playgroud)
它得出了结果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)
Run Code Online (Sandbox Code Playgroud)
小智 6
解决方案:1
const baseStyle = {
color: 'red',
backgroundColor: 'white'
}
const styles = StyleSheet.create({
style1: baseStyle,
style2: {
width: 100,
...baseStyle
}
})
Run Code Online (Sandbox Code Playgroud)
解决方案 2 使用样式化组件轻松管理和重用样式。
| 归档时间: |
|
| 查看次数: |
622 次 |
| 最近记录: |