react-native-web 学习笔记
React Native for Web
eact Native 转 web 方案:React Native for Web
“Learn once, write anywhere”是 react 提出的口号,在 react-native 开源后,这个口号得到了实现,我们只需要学会 react,就能同时在 web 端,安卓和 ios 开发应用。但是,react-native 在安卓和 ios 端能达到百分之九十以上的代码复用,却不能运行在移动 H5 端,我们不得不另外开发一套 H5 代码,以使应用能在手机浏览器上使用。react-native-web 就是这样一个将 react-native 应用转换成 H5 的库,以让我们能达到“Write one, run everywhere”。
官方资料
- Npm: https://www.npmjs.com/package/react-native-web
- Github: https://github.com/necolas/react-native-web
实现原理
在写代码之前,我们浅析一下这个库的实现。在我们的 react-native
代码中,所有的控件都是 import 自 react-native
import { View, Text, TextInput } from 'react-native';
那如果我们把这些组件全部在 web 上重新实现一遍,就能使其运行在 web 端了,用 div 代替 View,用 input 代替 TextInput,用 img 代替 Image,再加上相应的默认样式,这样我们写的 RN 代码就能平滑地迁移到 web 端,并且能在样式上基本保持一致性。react-native-web
就是这样一个库,他 react-native
的大部分组件都用 web 实现了一遍以达到我们的代码能在 web 运行的要求。
代码实现
在我们实现 web 端运行时,要尽量做到不侵入 RN 代码,不影响 RN 代码的逻辑,争取能够在基本不动 RN 项目代码的情况下,将其 H5 化。
这里我们先开始一个简单的 demo,首先使用 react-native-cli
初始化一个项目。
$ sudo npm i -g react-native-cli
$ react-native init rnweb
然后就可以编译原生 Android 或 ios 项目,使用模拟器打开了。而在 web 端我们需要使用 webpack 来编译运行代码,现在编写一个普通的 react 项目的 webpack.config.js
文件,与普通的 web 端 webpack 配置基本一致,唯一不同的是我们需要在 resolve 中加两项
{
resolve: {
alias: { 'react-native': 'react-native-web' },
modules: ['web_modules', 'node_modules'],
},
}
其中 alias 的别名使 RN 代码中 import 自 react-native 的组件指向了 react-native-web
。modules 是为了在某些依赖于 react-native
的第三方库无法直接转换成 H5 时,我们可以自行进行编写。
然后就可以运行 npm run web 打开网页了,
import React, { Component } from 'react';
import {
Platform,
StyleSheet,
Text,
View
} from 'react-native';
const instructions = Platform.select({
ios: 'Press Cmd+R to reload,\n' +
'Cmd+D or shake for dev menu',
android: 'Double tap R on your keyboard to reload,\n' +
'Shake or press menu button for dev menu',
web: 'Press Cmd+R or F12 reload'
});
export default class App extends Component {
render() {
return (
<View style={styles.container}>
<Text style={styles.welcome}>
Welcome to React Native!
</Text>
<Text style={styles.instructions}>
To get started, edit App.js
</Text>
<Text style={styles.instructions}>
{instructions}
</Text>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#F5FCFF',
},
welcome: {
fontSize: 20,
textAlign: 'center',
margin: 10,
},
instructions: {
textAlign: 'center',
color: '#333333',
marginBottom: 5,
},
});