首页 > 解决方案 > React Native Typescript 模板不起作用

问题描述

我使用官方命令(几次)创建了一个带有打字稿模板的 React Native 新项目,但react-native init MyApp --template typescript在运行应用程序时看不到我应用的更改。看起来热重载它的工作是刷新屏幕但不应用更改。在我创建没有打字稿的应用程序的情况下,它所有的工作都正常。

我没有收到任何错误,所以我不知道我能做什么。在它下面的 package.json 以防万一这有帮助,但它基本上是自动生成的文件typescript template

{
  "name": "MyApp",
  "version": "0.0.1",
  "private": true,
  "scripts": {
    "start": "node node_modules/react-native/local-cli/cli.js start",
    "test": "jest"
  },
  "dependencies": {
    "react": "16.6.3",
    "react-native": "0.58.4"
  },
  "devDependencies": {
    "@types/jest": "^24.0.0",
    "@types/react": "^16.8.2",
    "@types/react-native": "^0.57.34",
    "@types/react-test-renderer": "^16.8.0",
    "babel-core": "7.0.0-bridge.0",
    "babel-jest": "24.1.0",
    "jest": "24.1.0",
    "metro-react-native-babel-preset": "0.51.1",
    "react-test-renderer": "16.6.3",
    "ts-jest": "^23.10.5",
    "typescript": "^3.3.3"
  },
  "jest": {
    "preset": "react-native"
  }
}

tsconfig.json

{
  "compilerOptions": {
    "allowJs": true,
    "allowSyntheticDefaultImports": true,
    "esModuleInterop": true,
    "isolatedModules": true,
    "jsx": "react",
    "lib": ["es6"],
    "moduleResolution": "node",
    "noEmit": true,
    "strict": true,
    "target": "esnext"
  },
  "exclude": ["node_modules", "babel.config.js"]
}

知道如何使用 typescript 获得 react-native。谢谢!

标签: reactjstypescriptreact-native

解决方案


我找到了解决方案,基本上,当您使用项目的 ./ 中的 typescript模板创建react nativ e 应用程序时,出现了 2 个名为 App(App.js 和 App.tsx)的文件,因此基本上实现此工作的解决方案是转到 index.js 并替换

import App from './App';每次进口App from './App.tsx';

index.js

import {AppRegistry} from 'react-native';
import App from './App.tsx';
import {name as appName} from './app.json';

AppRegistry.registerComponent(appName, () => App);

您还可以解决删除.js文件的问题,以便索引指向.ts


推荐阅读