React Native 内联样式与 Stylesheet.create

ReactNative inline style vs Stylesheet.create

我运行今天遇到了一个问题。我想确保我的应用程序看起来不错,这需要我做很多调整,尤其是在 margin/padding 部分。

我的问题是:哪种方法更好?创建多个样式表(在父组件上)只是为了适应这些小的变化(我正在使用具有无边距样式表的可重用组件,这些边距将从父组件继承)或者让它内联在组件上?

我知道创建样式表可能是更好的方法。但是为了适应继承的样式,我将使用 style={[myComponentStyle, passedDownParentStyle]} <- 它不会创建一个新的样式表,然后首先使使用 Stylesheet.create 的目的无效吗?

任何这方面的专家都可以给我一些见解吗?

编辑 示例:

const Style = Stylesheet.create({
 child: {
  color: 'red'
 },
 parent1: {
  padding: 5,
  margin: 10
 },
 parent2: {
  padding: 10,
  margin: 5
 }
})

class Child {
 render() {
  return (
   <Text style={[Style.child, this.props.style]}>
    {this.props.children}
   </Text>
  )
 }
}

class Parent1 {
 render() {
  return (
   <Child style={Style.parent1}>
    Hello
   </Child>
  )
 }
}

class Parent2 {
 render() {
  return (
   <Child style={Style.parent2}>
    World
   </Child>
  )
 }
}

更新 我的问题是: style={[Style.child, this.props.style]} 的用法不是抵消了 Stylesheet.create 的目的吗?我不应该根本不使用它吗?

来自 React Native 文档:

Code quality:

  • By moving styles away from the render function, you're making the code easier to understand.
  • Naming the styles is a good way to add meaning to the low level components in the render function.

Performance:

  • Making a stylesheet from a style object makes it possible to refer to it by ID instead of creating a new style object every time.
  • It also allows to send the style only once through the bridge. All subsequent uses are going to refer an id (not implemented yet).

这就是我对为什么创建 Stylesheet 是更好的方法的理解。

现在回答你的问题:

我认为您可以传递一个样式图,将其与您的组件样式图结合起来,然后从两者的组合中创建一个样式表。或者,您可以将任何传递下来的样式视为对默认组件样式的覆盖,而只是将每个样式设为 Stylesheet (因为它只会使用一个或另一个)。 但是,如果子组件应该被父组件包裹,您可能根本不需要执行任何这些操作,因为样式可能已经被继承了。编辑:这是错误的,请忽略这部分)

如果您可以提供更多上下文和一些额外的代码,我可能会提供更深入的见解。

更新:

您也可以使用 StyleSheet.flatten(参见 here)。但是,它带有以下警告:

NOTE: Exercise caution as abusing this can tax you in terms of optimizations.

IDs enable optimizations through the bridge and memory in general. Refering to style objects directly will deprive you of these optimizations.

就像我之前说的,你可能想先把地图作为道具传递下去,然后在扁平化的地图上做Stylesheet.create(即道具一和默认的组合地图对于组件)。