【问题标题】:Issues creating simple react-native module for mobile and web为移动和 Web 创建简单的 react-native 模块的问题
【发布时间】:2020-01-01 17:01:54
【问题描述】:

我有一个关于创建一个简单的 React 模块的问题,该模块可以被移动和 React Native Web 使用。

我在 react native 模块中定义了简单的组件 - 请参阅下面的 index.js。 现在对于 react native web,需要将 index.js 翻译成 ES5(例如 /node_modules/.bin/babel src --out-file index.js)。但是,对于移动设备,它不需要翻译。

我的问题是如何让这个组件既可用于网络,又可作为反应模块的一部分? (因为 package.json 中只有一个主要属性)。

index.js

import React, { Component } from 'react';
import { Text } from 'react-native';

class DummyComponent extends Component {

    render () {
        return (
            <Text>hello World</Text>
        )
    }

}

export default DummyComponent;

package.json:

{
  "name": "react-test-module",
  "version": "1.0.0",
  "description": "test module",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "build": "./node_modules/.bin/babel src --out-file index.js"
  },
  "repository": {
    "type": "git",
    "url": ""
  },
  "author": "The man",
  "license": "MIT",
  "peerDependencies": {
    "react-native": "^0.61.5",
    "react": "^16.9.0",
    "react-dom": "^16.12.0"
  },
  "devDependencies": {
    "@babel/cli": "^7.7.7",
    "@babel/core": "^7.7.7",
    "@babel/preset-env": "^7.7.7",
    "@babel/preset-react": "^7.7.4",
    "react": "^16.12.0",
    "react-native": "^0.61.5",
    "react-dom": "^16.12.0"
  },
  "dependencies": {
    "@babel/plugin-proposal-class-properties": "^7.7.4",
    "react-native": "^0.61.5"
  }
}

【问题讨论】:

  • 将其提供给网络究竟是什么意思?如果你只想要 react-native-web 应该不需要编译,你可以引用你的普通 index.js 作为 package.json 中的主要入口点
  • 尝试使用 create-react-app for web。

标签: react-native react-native-android react-native-ios react-native-web


【解决方案1】:

因此,如果您想要两个不同的版本,您可以为索引文件使用特定于平台的扩展名。

您可以为index.js 创建三个文件,因此一个只是index.js,您可以将其用于可以翻译的网络版本,您可以创建两个不同的文件

index.ios.jsindex.android.js 将用于移动设备,它们可以与您现在拥有的文件完全相同。

这两个文件将由您运行的平台自动选取。

【讨论】:

    【解决方案2】:

    只需使用react-native-web,无需使用任何其他翻译。

    你可以参考非常好的文档here

    如果你想使用创建 React 应用

    npx create-react-app my-app
    cd my-app
    npm install react-native-web
    npm start
    

    如果是独立应用,请按照步骤here

    【讨论】:

      【解决方案3】:

      如果你想让这个组件同时在 React Web 应用和 React Native 上工作,我认为 ReactXP 应该是你想要的

      import React, { Component } from 'react';
      import { Text } from 'reactxp';
      
      class DummyComponent extends RX.Component {
          render () {
              return (
                  <RX.Text>Hello World</RX.Text>
              )
          }
      
      }
      
      export default DummyComponent;
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2019-02-28
        • 2021-12-24
        • 1970-01-01
        • 1970-01-01
        • 2022-09-30
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多