javascript - 如何在 React Native 的 StyleSheet.create 中继承样式(可能使用解构语法)

标签 javascript react-native ecmascript-6 react-native-stylesheet

我想在 StyleSheet.create 的参数对象中重用样式,该怎么做?

查看代码:

const styles = StyleSheet.create({
  style1: {
    color: "red",
    backgroundColor: "white"
  },
  style2: {
    width: 100,
    ...style1
  }
})

本来我想让style2继承style1的所有colorbackgroundColor,再扩展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/

相关文章:

javascript - Laravel 5.2 和 jQuery 验证 :Trying to get property of Non-Object

javascript - 单击正文关闭侧边菜单

javascript - 如何加载动态数据到react-native-chart-kit?

javascript - 如何确保 React props 的类型正确

javascript - 如果在更新下拉菜单时网络服务不可用怎么办?

javascript - 在 Meteor 应用程序中实现 MongoDB 2.4 的全文搜索

react-native - 使用 RN、React Navigation 和 React Native Web 的通用应用程序最佳实践

reactjs - 如何在 Typescript 中定义 React Navigation navigationOptions 参数

javascript - ES6 - 有条件地在 Promise 中发出重试信号,直到达到最大重试次数

javascript - ES6 类实例化中的错误消息