在 React Native 上使用样式化组件级联文本颜色

Cascade text color with Styled Components on React Native

我正在尝试使用 React Native 创建一个组件,该组件在包装组件内包含一个 <Text> 组件:

const MyComponent = props => (
  <View {...props}>
   <Text {...props}>Hello world</Text>
  <View>
)

const MyRedComponent = styled(MyComponent)`
  color: #000;
  margin-left: 10px;
  background: #F00;
`

我正在以这种方式编写我的组件,因此我可以在更改背景颜色时从相同样式的组件更改文本颜色:

const MyBlueComponent = styled(MyRedComponent)`
  color: #FFF;
  background: #00F;
`

然而,这种方法存在一个问题,即所有样式都应用于 <Text> 组件,而不仅仅是 color;在此示例中,<Text> 组件还从父样式中获取 margin-left 样式,这不是首选。我只希望将文本颜色级联到 <Text> 组件。

是否可以将样式化组件与 React Native 结合使用?

您可以使用 StyleSheet.flatten 创建包装函数并从生成的对象中选择颜色:

const MyComponent = props => (
  <View {...props}>
    <Text style={{ color: StyleSheet.flatten(props.styles).color }}>Hello world</Text>
  <View>
)

const MyRedComponent = styled(MyComponent)`
  color: #000;
  margin-left: 10px;
  background: #F00;
`

将采摘提取到它自己的功能是有意义的。例如,您可以创建以下包装器:

const pickColorFromStyles = styles => {
  const { color } = StyleSheet.flatten(styles)
  return { color }
}

...并在您的组件中使用该函数:

const MyComponent = props => (
  <View {...props}>
    <Text style={pickColorFromStyles(props.styles)}>Hello world</Text>
  <View>
)

注意文档页面中使用 StyleSheet.flatten 时的警告:

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.