【问题标题】:Can we use rems to style a component in react native我们可以在 react native 中使用 rems 来设置组件的样式吗
【发布时间】:2020-06-04 13:59:30
【问题描述】:

我想使用rems 进行样式设置,就像我通常在其他 CSS 项目中所做的那样。但我不明白如何让这个工作。这似乎根本不起作用。

const styles = StyleSheet.create({
  header: {
    fontSize: 3rem,
    fontWeight: 400
  }
});

【问题讨论】:

    标签: css react-native


    【解决方案1】:

    不需要任何额外的模块,直接声明为字符串即可:

      const styleHighlight = {
        color: 'red',
        fontSize: '5rem',
        fontWeight: 'bold',
        backgroundColor: 'yellow'
      }
      return (
        <div>
          <p style={styleHighlight}>React paragraph JSX</p>
        </div>
      )
    

    【讨论】:

      【解决方案2】:

      是的,你可以!使用this npm 包你可以轻松做到。

      步骤

      1. 运行npm i react-native-extended-stylesheet --save
      2. 使用EStyleSheet.create() 而不是StyleSheet.create(): 定义样式

      简单示例:

      /* component.js */
      import EStyleSheet from 'react-native-extended-stylesheet';
      
      // define extended styles 
      const styles = EStyleSheet.create({
        column: {
          width: '80%'                                    // 80% of screen width
        },
        text: {
          color: '$textColor',                            // global variable $textColor
          fontSize: '1.5rem'                              // relative REM unit
        },
        '@media (min-width: 350) and (max-width: 500)': { // media queries
          text: {
            fontSize: '2rem',
          }
        }
      });
      
      // use styles as usual
      class MyComponent extends React.Component {
        render() {
          return (
            <View style={styles.column}>
              <Text style={styles.text}>Hello</Text>
            </View>
          );
        }
      }  
      

      【讨论】:

      • 这意味着rem 默认不被接受(“native” RN),比如percentagepixels 对吧?
      • @Felix 你是对的,rem 不是受支持的布局道具,根据RN docs,只有点数或百分比。与Text style props 相同,对于 fontSize 仅支持点。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-05-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-07-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多