React native 在React Native中映射对象

React native 在React Native中映射对象,react-native,React Native,我是新来的。现在,我正在学习道具和状态。我想试试这个文档中的FlatList组件。然而,我得到了这个错误 您正在使用称为类型脚本的类型化JavaScript 如果您想使用TypeScript,我强烈建议您使用它,那么您可以按照以下教程进行操作: 迁移到TypeScript: 只是为了摆脱错误 类型脚本迁移继续 添加打字脚本 下一步是将TypeScript添加到项目中。以下命令将: 将TypeScript添加到项目中 将React Native TypeScript Transformer添加到项

我是新来的。现在,我正在学习道具和状态。我想试试这个文档中的FlatList组件。然而,我得到了这个错误


您正在使用称为类型脚本的类型化JavaScript

如果您想使用TypeScript,我强烈建议您使用它,那么您可以按照以下教程进行操作:

迁移到TypeScript:

只是为了摆脱错误

类型脚本迁移继续

添加打字脚本

下一步是将TypeScript添加到项目中。以下命令将:

将TypeScript添加到项目中 将React Native TypeScript Transformer添加到项目中 初始化一个空的TypeScript配置文件,我们将在下一步进行配置 添加一个空的React Native TypeScript Transformer配置文件,我们将在下一步进行配置 为React和React Native添加键入 好的,让我们继续运行这些

yarn add --dev typescript
yarn add --dev react-native-typescript-transformer
yarn tsc --init --pretty --jsx react
touch rn-cli.config.js
yarn add --dev @types/react @types/react-native
tsconfig.json文件包含TypeScript编译器的所有设置。通过上面的命令创建的默认值基本上是好的,但是打开文件并取消注释以下行:

 {
  /* Search the config file for the following line and uncomment it. */
  // "allowSyntheticDefaultImports": true,  /* Allow default imports from modules with no default export. This does not affect code emit, just typechecking. */
}
rn-cli.config.js包含React Native TypeScript转换器的设置。打开它并添加以下内容:

module.exports = {
  getTransformModulePath() {
    return require.resolve('react-native-typescript-transformer');
  },
  getSourceExts() {
    return ['ts', 'tsx'];
  },
};
迁移到TypeScript

将生成的App.js和_tests_u/App.js文件重命名为App.tsx。index.js需要使用.js扩展名。如果文件不包含任何JSX,则所有新文件都应使用.tsx扩展名或.ts

如果您现在尝试运行该应用程序,您会得到一个错误,比如对象原型可能只是一个对象或null。这是由于未能从React导入默认导出以及同一行上的命名导出而导致的。打开App.tsx并修改文件顶部的导入:

-import React, { Component } from 'react';
+import React from 'react'
+import { Component } from 'react';
其中一些原因与Babel和TypeScript如何与CommonJS模块互操作有关。在未来,这两种行为将趋于稳定

此时,您应该能够运行React本机应用程序

-import React, { Component } from 'react';
+import React from 'react'
+import { Component } from 'react';