【问题标题】:How to inherit style within StyleSheet.create in React Native (using destructuring syntax maybe)如何在 React Native 中的 StyleSheet.create 中继承样式(可能使用解构语法)
【发布时间】:2020-01-31 11:32:17
【问题描述】:

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

查看代码:

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

最初,我希望style2style1 继承所有colorbackgroundColor,并再扩展1 个名为width 的属性。所以我确实尝试了上面的代码,但随后出现错误“未声明 style1”。 我意识到了这个问题,所以我用...this.style1 替换了...style1,错误消失了,但它并没有像我预期的那样工作。我想知道为什么并尝试在 javascript 中运行这个 sn-p 来测试行为:

styles = {
  style1: {
    color: "red",
    backgroundColor: "white"
  },
  style2: {
    width: 100,
    inherit: this.style1
  }
}
console.log(styles.style2.inherit)

它输出了结果undefined,而不是styles.style1。我再次意识到这个问题,在用 inherit: styles.style1 替换 inherit: this.style1 后,javascript sn-p 可以工作,但在 React Native 代码中不是

我想直到现在,你都明白我想要什么,所以我的问题是我怎样才能实现这一点(在 React Native 中重用样式代码)?我认为会有很多解决方法,所以请尽可能多地给我。谢谢。

这是我尝试过但没有得到预期结果的语法列表(或者因为我的大脑工作不好,我错了):

...style1
...this.style1
...styles.style1
...StyleSheet.style1
...StyleSheet.flatten(styles.style1)

【问题讨论】:

  • 我对 React Native 很陌生,所以如果我的问题有问题,请原谅我。

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


【解决方案1】:

不可能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 轻松管理和重用样式。

【讨论】:

  • 稍后我会看看Styled Components。非常感谢。
【解决方案2】:

我知道一种解决方法是将“可重用”style1 对象放在StyleSheet.create 之外:

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

有没有更好的方法?因为style1也可以是其他元素使用的样式,所以我不能再使用<Element style={styles.style1}/>了……

【讨论】:

    猜你喜欢
    • 2017-07-19
    • 1970-01-01
    • 2020-09-02
    • 2021-12-29
    • 1970-01-01
    • 1970-01-01
    • 2020-08-02
    • 2018-04-27
    • 1970-01-01
    相关资源
    最近更新 更多