美文网首页React Native学习
在web、iOS,Android端共同使用React初探(二)

在web、iOS,Android端共同使用React初探(二)

作者: 羽纱 | 来源:发表于2018-01-10 09:45 被阅读314次

react-native-web中可以看到如果只是使用RN的自带组件,那经过一定配置可以对代码0修改即可在web端使用。它是通过在webpack中配置别名,将react-native包重定向到react-native-web包中,在react-native-web包中,用Web端ReactJS重写了RN中几乎所有组件和API,让react-native-web的使用方式和react-native的使用方式几乎毫无区别,样式上也做了raect-nativeweb上的转化。我们先体验一下效果。

注:以下代码都是在在web、iOS,Android端共同使用React初探(一)的基础上继续集成的。

第一步:导入react-native-web

yarn add react-native-web
yarn add --dev babel-plugin-react-native-web

修改.babelrc文件:

"plugins": ["react-native-web"]

使用babel-plugin-react-native-web能将设置react-native设置为react-navite-web的别名。

第二步:web和react-native使用同一套代码

1、删除App.web.js
2、修改webpack.config.json

...
const babelLoaderConfiguration = {
    test: /(\.jsx|\.js)$/,
    // Add every directory that needs to be compiled by Babel during the build.
    include: [
        path.resolve(appDirectory, 'index.web.js'),
        path.resolve(appDirectory, 'src'),
    ],
    use: {
        loader: 'babel-loader',
        options: {
            cacheDirectory: true,
            // Babel configuration (or use .babelrc)
            // This aliases 'react-native' to 'react-native-web' and includes only
            // the modules needed by the app.
            plugins: ['react-native-web'],
            // The 'react-native' preset is recommended to match React Native's packager
            presets: ['react-native']
        }
    },
};
...

3、修改App.js

....
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: 'hotload',
});
...

4、修改index.web.js:

import App from './src/App';
import React from 'react';
import { AppRegistry } from 'react-native';

// register the app
AppRegistry.registerComponent('ReactAndNativeDemo', () => App);

AppRegistry.runApplication('ReactAndNativeDemo', {
    initialProps: {},
    rootTag: document.getElementById('root')
});

第三步:运行代码

npm run webStart
npm run webServer

效果如下:


image.png

总结

优点:
通过以上的配置和修改,我们实现了React Native 和 ReactJS web使用同一个Component来渲染界面,通过Platform.select来写特定平台的代码。
缺点:
有些RN的组件在react-native-web上是没有的,例如ViewPagerAndroid,在RN的常用组件react-navigationreact-native-swiper中都有用到,这时候很难利用react-native-web使用这些组件。另外在react-native-web中还有一些组件的表现形式与react-native不同,例如Image
所以不能完全依赖react-native-web,想着懒懒的无缝转换RN应用到Web端,该改的改,该重写的重写,它能减轻大部分工作,但不是全部。

github地址https://github.com/lyxia/ReactAndNativeDemo

相关文章

网友评论

  • 后浪普拉斯:react-native-web 只能解析对应react-native 的控件,我们自己定义的页面控件要怎么处理呢?

本文标题:在web、iOS,Android端共同使用React初探(二)

本文链接:https://www.haomeiwen.com/subject/iogwnxtx.html