首先,React Native 和 React 应用的样式引用是有区别的。
在React中,样式可以写在一个css/less/sass文件中,引用样式的方式是在html中的link标签引入,也可以在js文件中引入,这里一定要注意,必须使用css-loader和style-loader,要不会报错,“module not found“!
import './style.css';//引入css文件
class App extends Component {
render() {
return (
}
}
而在React-Native中,有两种引入方式,一种是内联样式,一种是定义样式对象,记住–这个样式是写在js文件中,我们使用的方式是以对象的方式来定义样式
import React, { Component } from 'react';
import { AppRegistry, StyleSheet, Text, View } from 'react-native';
export default class LotsOfStyles extends Component {
render() {
return (
just red
just bigblue
bigblue, then red
red, then bigblue
);
}
}
const styles = StyleSheet.create({
bigblue: {
color: 'blue',
fontWeight: 'bold',
fontSize: 30,
},
red: {
color: 'red',
},
});
All the React Native components accept a style property. The value can be a registered object, a plain object, or an array.
所有的React Native 组件接受一个style的属性,这个属性的值可以是已注册的对象,简单对象,或者一个数组
同时,需要知道React Native并不是支持所有的浏览器CSS属性,它仅仅支持常见的部分属性,详见 >> react-native css支持属性
那么,回到上面的问题。为什么Twitter可以使用React Native的技术在网页端显示呢?查了一下,发现是用了一个叫做
而React Native for Web做了什么事呢?
React Native for Web transforms React Native styles into React DOM styles. Any styles defined using StyleSheet.create will ultimately be rendered using CSS class names.
React Native for Web 将React Native 的样式转换为React Dom的样式。任何使用StyleSheet.creat方法创建的样式最终都会渲染成带有class名字的CSS样式属性。
这里有个例子:
input:
const Box = () =>
const styles = StyleSheet.create({
box: {
margin: 0
}
});
output
.rn-1mnahxq { margin-top: 0px; }
.rn-61z16t { margin-right: 0px; }
.rn-p1pxzi { margin-bottom: 0px; }
.rn-11wrixw { margin-left: 0px; }
至于页面上为啥只有一个标签,而没有实际的css代码,是因为样式并不是以css的形式存储,而是一个JS对象。关于这一点,涉及篇幅较长,这里不展开讨论,掘金上的这一篇文章具体分析了代码是如何实现这个功能的,可以看一看
最后,关于能否在页面上查看CSS的内容。可以打开chrome的console面板,输入$0.sheet查看具体对象。写得有点啰嗦,希望能够帮到你