0

作为 React 的新手,我被一些看似非常简单的东西所困扰。不知道做错了什么。

我有一个像这样的组件BasicReactComponent.js

import React from 'react';

const BasicReactComp = () => {
  console.log('hi');
  return (
    <div>
      I was loaded from basic react comp.
    </div>
  );
};

export default BasicReactComp;

我试图在我的主文件中调用它,如下所示:

import React from 'react';
import ReactDOM from 'react-dom';
const BasicReactComp = require('./BasicReactComp');

ReactDOM.render(
 <BasicReactComp />,
 document.getElementById('foo')
);

我不断收到以下错误

**Invariant Violation: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: object.
    Invariant Violation: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: object.**
4

1 回答 1

2

在 ES6 模块和 CommonJS 模块之间进行转换时,默认导出作为default 属性导出。因此,您必须访问.default您的值require

const BasicReactComp = require('./BasicReactComp').default;

或者使用以下import语法:

import BasicReactComp from './BasicReactComp';
于 2017-06-05T04:52:25.993 回答