【问题标题】:React - Invariant Violation exception [duplicate]React - 不变违规异常[重复]
【发布时间】:2017-11-05 19:22:26
【问题描述】:

刚接触 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.**

【问题讨论】:

  • 使用import BasicReactComp from './BasicReactComp'

标签: javascript reactjs react-component react-dom


【解决方案1】:

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

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

或者使用import 语法:

import BasicReactComp from './BasicReactComp';

【讨论】:

  • #FacePalm.... 非常感谢... 已经解决了 :)
  • @felix-king,你知道是否有办法让我做这样的事情... $('#foo').append(ReactDOM.render( , document.createElement('div') ));由于某种原因它不起作用......问题是我希望将组件呈现在附加到另一个元素的 div 中
  • 没关系 :)
猜你喜欢
  • 1970-01-01
  • 2017-10-24
  • 2018-07-07
  • 2017-02-27
  • 1970-01-01
  • 1970-01-01
  • 2016-06-10
  • 2018-10-04
  • 2015-07-18
相关资源
最近更新 更多