未捕获错误:不变冲突:元素类型无效:需要字符串(对于内置组件)或类/函数,但得到:对象

2022-08-29 22:30:47

我收到此错误:

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

这是我的代码:

var React = require('react')
var ReactDOM =  require('react-dom')
var Router = require('react-router')
var Route = Router.Route
var Link = Router.Link

var App = React.createClass({
  render() {
    return (
      <div>
        <h1>App</h1>
        <ul>
          <li><Link to="/about">About</Link></li>
        </ul>
      </div>
    )
  }
})

var About = require('./components/Home')
ReactDOM.render((
  <Router>
    <Route path="/" component={App}>
      <Route path="about" component={About} />
    </Route>
  </Router>
), document.body)

我的文件:Home.jsx

var React = require('react');
var RaisedButton = require('material-ui/lib/raised-button');

var Home = React.createClass({
  render:function() {
    return (
        <RaisedButton label="Default" />
    );
  },
});

module.exports = Home;

答案 1

在我的情况下(使用Webpack),它是以下两者的区别:

import {MyComponent} from '../components/xyz.js';

import MyComponent from '../components/xyz.js';

第二个工作,而第一个导致错误。反之亦然。


答案 2

您需要导出默认值或 require(path).default

var About = require('./components/Home').default