如何使用样式化组件在 React Native 中设置文本子级的样式?

问题描述 投票:0回答:3

所以如果我有这个

const MyView = styled.View`
    background: green;
    color: red;
`

我有

<MyView>
  <Text> Hello </Text>
</MyView>

文字不是红色

所以我尝试了

const MyView = styled.View`
    background: green;
    & > Text { color: red; }
`

你可以在 React 中使用普通的样式组件来做到这一点,但是文本仍然不是红色的

我该如何实现这一目标?

我知道我能行

const StyledText = styled.Text`
    color: red;
`

然后

    <MyView>
      <StyledText> Hello </StyledText>
    </MyView>

但如果可以的话我想避免这种情况。是否可以访问 RN 中的 Text 子元素?

reactjs react-native styled-components
3个回答
16
投票

不幸的是,RN 的样式组件只是一个包装器,它返回带有样式属性

<View style={...styles} />
的通用 RN 视图(或文本)。无法在父块中设置子元素的样式。


1
投票

就像 Batraz Jioty 在他的回答中提到的那样,我认为这是不可能的。 RN 中的风格继承非常有限。我相信你可以实现这样的事情,只需将一个放入另一个中,但从观点来看,我认为这是不可能的


0
投票

如前所述,CSS 之类的样式覆盖在 React Native 中是不可能的。
但是,有一种模式允许为子元素设置样式,但不涉及样式库:

function TextRed({ children }) {
  return React.cloneElement(children, {style: { color: 'red' }})
}

这是我知道的唯一方法,在某些情况下它非常有用!

© www.soinside.com 2019 - 2024. All rights reserved.