React Native中的Map对象

时间:2018-10-09 15:05:39

标签: react-native

我是React Native的新手。现在,我正在学习道具和状态。我想尝试这份文档https://facebook.github.io/react-native/docs/flatlist中的FlatList组件。但是,我收到此错误。

enter image description here

1 个答案:

答案 0 :(得分:0)

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

如果您想使用TypeScript(强烈建议您使用,请按照以下教程操作):

  

迁移到TypeScript:

https://facebook.github.io/react-native/blog/2018/05/07/using-typescript-with-react-native

  

要摆脱错误!

state = {selected : (new Map())};

TypeScript迁移继续...

添加TypeScript

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

  • 将TypeScript添加到您的项目中
  • 将React Native TypeScript转换器添加到您的项目中
  • 初始化一个空的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_ / App.js文件重命名为App.tsx。 index.js需要使用.js扩展名。所有新文件都应使用.tsx扩展名(如果文件不包含任何JSX,则应使用.ts)。

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

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

其中某些原因与Babel和TypeScript与CommonJS模块的互操作方式不同。将来,两者将保持相同的行为。

此时,您应该能够运行React Native应用程序。

相关问题