【问题标题】:React-Native styling using CSS stylesheets and class names使用 CSS 样式表和类名的 React-Native 样式
【发布时间】:2018-01-24 09:37:17
【问题描述】:

我刚刚开始开发一个 react-native 应用程序。 official docs suggest 使用 JavaScript 对象为您的组件创建样式,就像这样,

<Text style={style.text}>Blah Blah</Text>
const style = {
    text: {
        fontSize: 20
    }
}

我正在尝试将 className 添加到 Text 属性,因此我可以使用简单的样式表添加 css。这甚至可以用 react-native 实现吗(我知道我们可以在 react 中做到这一点)?像这样的,

<Text className="text-style"></Text>

// from CSS file
text-style: {
    font-size: 20;
}

【问题讨论】:

  • 不,据我所知,它不会起作用。您可以查看 SO 的有关样式的文档以获取详细信息
  • 不,据我所知,你不能在 react native 中使用 css 类。

标签: css react-native classname


【解决方案1】:

React Native 使用 CSS 样式的方式是 StyleSheet 对象是 CSS 作为一种语言的 js 副本。您需要做的就是创建一个 .js 并导入包含 StyleSheet 对象的 js 对象。

StyleSheet JS 对象的示例是:

import { StyleSheet } from 'react-native'; 

const styles = StyleSheet.create({
  textStyle: {
    fontSize: 20,
  },
  otherStyle: {
    position: 'absolute',
    justifyContent: 'center',
  }
});

基本上它需要的是一个遵循StyleSheet API 的对象数组。一个好的经验法则是将你知道的 css 样式写成驼峰式,例如justifyContent 而不是 justify-content,React Native 引擎会尽力通过使用这些 StyleSheet 对象来复制 CSS,阅读文档和示例将帮助您了解 StyleSheet 的能力和不能力(提示:@ 987654329@ 和 Dimensions API 非常棒,百分比是像 '50%' 这样的字符串。

【讨论】:

  • 它不是 CSS 的复制品——您将 JSON 对象传递给 StylesSheet.create,API 不同,并且不存在浏览器规范。
【解决方案2】:

react-native 中没有 className,但您可以像这样在 react-native 中使用样式对象:

<Text style={textStyle}>Some Words</Text>

const textStyle = {
    fontSize: 20
}

注意:某些样式属性的名称不同。例如 css font-size 在 react-native 中是 fontSize

【讨论】:

  • text-style 语法不正确,无法使用。你不能在这样的变量名中使用破折号。
【解决方案3】:

需要配置 react native sass /css 转换器 https://github.com/kristerkari/react-native-sass-transformer

将 JSX className 属性转换为在 React Native 中运行时计算样式的样式属性。该插件用于将包含已解析 CSS 媒体查询和 CSS 视口单元的样式对象与 React Native 进行匹配。

请查看此链接:https://github.com/kristerkari/babel-plugin-react-native-classname-to-dynamic-style

当使用 React native typescript 时,你也需要安装这个包 https://github.com/kristerkari/react-native-types-for-css-modules

【讨论】:

    【解决方案4】:

    文档所指的对象是 JSX 中的 StyleSheet 对象。您需要从react-native 导入StyleSheet。您在此处写入const 变量的样式将进入您将使用StyleSheet 创建的对象。

    import {StyleSheet} from 'react-native';
    var styles = StyleSheet.create({
      container: {
        flex: 1,
        flexDirection: 'column',
        justifyContent: 'space-evenly',
        backgroundColor: '#0070af',
        alignItems: 'center',
        backgroundColor:'#0070af'
      },
      textstyle:{
        color:'white',
        fontFamily: "Roboto",
      }});
    
    export default styles;
    

    【讨论】:

      猜你喜欢
      • 2021-07-23
      • 2020-09-21
      • 2019-07-27
      • 2019-03-07
      • 1970-01-01
      • 2016-02-09
      • 1970-01-01
      • 2021-06-30
      • 1970-01-01
      相关资源
      最近更新 更多