React JSX文件给出错误"无法读取未定义的属性'createElement'"

Som*_*Guy 78 javascript npm reactjs react-jsx

我有一个运行的文件test_stuff.js npm test

它几乎看起来像这样:

import { assert } from 'assert';
import { MyProvider } from '../src/index';
import { React } from 'react';

const myProvider = (
  <MyProvider>
  </MyProvider>
);

describe('Array', function() {
  describe('#indexOf()', function() {
    it('should return -1 when the value is not present', function() {
      assert.equal(-1, [1,2,3].indexOf(4));
    });
  });
});
Run Code Online (Sandbox Code Playgroud)

不幸的是,我收到了错误

/Users/me/projects/myproj/test/test_stuff.js:11
var myProvider = _react.React.createElement(_index.MyProvider, null);
                             ^

TypeError: Cannot read property 'createElement' of undefined
    at Object.<anonymous> (/Users/me/projects/myproj/test/test_stuff.js:7:7)
Run Code Online (Sandbox Code Playgroud)

那是什么意思?我正在成功地从'react'导入React,为什么React会被取消定义?它是_react.React,无论那意味着什么......

Kaf*_*afo 140

要导入React,请import React from 'react'在导入的内容不是该模块或文件中的默认导出时添加括号.如果出现反应,则为默认导出.

这可能适用于您的其他导入,具体取决于您的定义方式.

  • 我不知道为什么会这样但对我来说它是'import*,因为React来自"反应"` (12认同)
  • 从技术上讲,`import React from'alse''无效,因为React不是默认导出,但是由于将ES6与babel一起使用,它可以正常工作.也许你的babel配置是不同的,迫使你使用正确的有效语法,即`import*as React from'alse''.欲了解更多信息:https://github.com/DefinitelyTyped/DefinitelyTyped/issues/5128 (8认同)
  • 我正在使用 React-native 和 expo,我的 babel 预设是 `babel-preset-expo` https://github.com/expo/babel-preset-expo/blob/master/index.js (2认同)
  • 如果使用打字稿,则导入样式也将受tsconfig中esModuleInterop设置的影响。tsconfig必须应用于测试文件(检查`include`和`files`)。 (2认同)

小智 21

import React, { Component } from 'react'
Run Code Online (Sandbox Code Playgroud)

这对我有用.我不知道为什么它修复了我的这个问题的版本.因此,如果你是偶然发现这个问题并且使用create-react-app作为起始样板的人,那么这种导入React的方法就可以了.(截至18年10月,哈哈)


Khu*_*ong 13

对于那些使用TypeScript使用ReactJS的人。

import * as React from 'react';
Run Code Online (Sandbox Code Playgroud)

  • 有一种方法可以让 import“再次美丽”。将“esModuleInterop: true”添加到 tsconfig.json。并享受您的“从'react'导入React”!——舒利克·弗拉基米尔 (4认同)
  • 这是我的问题。谢谢! (2认同)
  • 为什么这是必要的?运行笑话时,我在整个代码库中都收到此错误。 (2认同)

Vim*_*Sam 13

由于粗心,我发生了这个错误。其实是

import React from 'react';
Run Code Online (Sandbox Code Playgroud)

括号用于命名导出,如下所示:

import React, { useState, useEffect } from 'react';
Run Code Online (Sandbox Code Playgroud)


小智 8

从 React 导入 React 时出现此问题,我将其放在大括号内。

请这样做:

import React, {useState} from "react";

代替:

import {React, useState} from "react";


归档时间:

查看次数:

39819 次

最近记录:

6 年,3 月 前