React-使用CSS样式表和类名的本机样式

uinbv5nw  于 2022-12-19  发布在  React
关注(0)|答案(6)|浏览(170)

我刚刚开始开发一个React Native 应用,official docs suggest使用JavaScript对象为组件创建样式,如下所示:

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

我尝试在Text属性中添加一个className,这样我就可以使用简单的样式表添加css。这在react-native中是否可行(不过我知道我们可以在react中做到这一点)?

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

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

gtlvzcf81#

React Native处理CSS样式的方式是StyleSheet对象是CSS作为一种语言的js副本。您所需要做的就是创建一个.js并导入包含StyleSheet对象的js对象。
StyleSheetJS对象的一个例子是:

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的功能并且不能(提示:flexDimensions API非常棒,百分比是'50%'这样的字符串)。

brqmpdu1

brqmpdu12#

react-native中没有className,但您可以在react-native中使用样式对象,如下所示:

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

const textStyle = {
    fontSize: 20
}

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

xriantvc

xriantvc3#

需要配置React Nativesass /css转换器https://github.com/kristerkari/react-native-sass-transformer
在React Native中将JSX className属性转换为在运行时计算样式的样式属性。该插件用于将包含已解析CSS媒体查询和CSS视口单元的样式对象与React Native进行匹配。
请查看此链接:https://github.com/kristerkari/babel-plugin-react-native-classname-to-dynamic-style
当使用React原生类型脚本时,您还需要安装此软件包https://github.com/kristerkari/react-native-types-for-css-modules

ma8fv8wu

ma8fv8wu4#

文档中提到的对象是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;
piok6c0g

piok6c0g5#

首先你需要从react-native导入样式表,然后创建带有样式的对象。

import { StyleSheet, View } from "react-native"

const Home = () => {
  return(
    <View style={styles.container}></View>
  )
}

const styles = StyleSheet.create({
  container: {
    backgroundColor: blue,
    height: "100%",
  }
})
6fe3ivhb

6fe3ivhb6#

我不知道为什么没有人提到这一点,但我认为这是更好的。
How can I use CSS in ReactNative
创建一个名为App.moudle.css的文件来编写纯传统的css。并像这样导入它-

import style from './App.module.css';

<View style={style.container}>

这会更好,因为它会增加react和react-native的共享代码。
令我非常失望的是,还没有一种方法可以在react-native中使用css类。

相关问题