【问题标题】:How to merge styles defined in defaultProps with inline styles in React Native?如何将 defaultProps 中定义的样式与 React Native 中的内联样式合并?
【发布时间】:2022-11-23 06:52:07
【问题描述】:

我必须在 React 提供的 Text 组件上定义一些默认样式。我这样做是这样的:

 @ts-ignore
 Text.defaultProps.style = {fontWeight: '100'}

我必须在 Text 组件上定义一些其他样式,这些样式特定于使用 Text 组件的位置。但是当我尝试使用内联样式在 Text 组件中提供样式时,它似乎覆盖了我拥有的 defaultProps.style 。

<Text style={{color: 'white'}}> // this text only has white color but not fontWeight that was defined in defaultProps.

有没有办法在使用反应提供的文本组件的同时合并它们?

我尝试了以下方法:

<Text style={{...this.props.style, color:'white'}}>

我也试过这个:

<Text style={[this.props.style, {color:'white'}]} >

这两个似乎都不起作用。

【问题讨论】:

    标签: reactjs react-native styling


    【解决方案1】:

    样式被覆盖,因为默认值没有合并与风格。如果没有传入样式,将使用默认样式,但如果传入任何样式,默认对象将被新样式对象覆盖。

    一般来说,我不鼓励你在内置组件上设置默认属性。它会使代码难以遵循,并且不会以您想要的方式帮助您。此外,React 就是为此而构建的。这是一个打字稿示例:

    interface Props {
      style?: StyleProp<TextStyle>;
      children?: string;
    }
    
    const defaultStyle = StyleSheet.create({
      default: {
        color: 'black',
      }
    });
    
    const MyText: React.FC<Props> = ({ style, children }) => {
      return <Text style={[ defaultStyles.default, style ]}>{children}</Text>
    }
    

    当您将样式放入上面的数组中时,它们将从头到尾逐渐合并。所以如果你写

      <MyText style={{ color: 'white' }}>Text</MyText>
    

    道具样式将覆盖默认样式中的颜色。但是,如果你这样做

      <MyText style={{ textDecoration: 'underline' }}>Text</MyText>
    

    最终的样式表将被合并,并同时具有 colortextDecoration 属性。有关更多信息,请参阅the docs

    【讨论】:

      猜你喜欢
      • 2018-07-27
      • 2017-07-19
      • 2017-02-28
      • 2020-02-15
      • 2017-01-13
      • 1970-01-01
      • 2016-12-11
      • 2018-06-08
      • 2016-09-25
      相关资源
      最近更新 更多