【问题标题】:Cant use a class from import file无法使用导入文件中的类
【发布时间】:2017-04-24 20:16:27
【问题描述】:

我正在尝试将一个项目拆分为多个文件,当我尝试导入一个文件时,我收到了此警告/错误 warning.js:36Warning: React.createElement: type should not be null, undefined, boolean, or number. It should be a string (for DOM elements) or a ReactClass (for composite components). Check the render method ofMenu. warning.js:36Warning: React.createElement: type should not be null, undefined, boolean, or number. It should be a string (for DOM elements) or a ReactClass (for composite components). Check the render method ofMenu. invariant.js:38 Uncaught Error: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined. Check the render method ofMenu.(…)

我尝试用谷歌搜索这个问题,我看到很多类似这样的帖子,但我无法解决这个问题。 这是 Menu.jsx

import React, { Component } from 'react' 
import { render } from 'react-dom'
import Link from 'react-router'

export default class Menu extends Component {
    render () {
        return (
            <ul>
                <li><Link to="test">Link1</Link></li>
                <li><Link to="test2">Link2</Link></li>
            </ul>
        )
    };
}

这里是 app.jsx

import React from 'react'
import { render } from 'react-dom'
import { Router, Route, Link, browserHistory } from 'react-router'
import Menu from './Menu'

const Home = React.createClass({
  render() {
    return (
      <div>
        <div className="headerNav">
          <Menu />
        </div>
        <h1>Welcome to the Home Page</h1>
        {this.props.children}
      </div>
    );
  }
});

const RestOf = React.createClass({
  render: function() {
    return (<h1>Will it get all the others ?</h1>);
  }
});

render((
  <Router history={browserHistory}> 
    <Route path="/" component={Home} > 
      <Route path="*" component={RestOf} />
    </Route> 
  </Router>
), document.getElementById('root')); 

好吧,我几乎尝试了从搜索中找到的所有内容,不确定我在这里缺少什么 tbh .. 但我真的对这些错误感到困惑。 p.s 我是 React 的新手。

如果我将 Menu 类放在 app.jsx 中并将其定义为其他类,它会正常工作。

编辑:我正在使用 webpack,所以编译反应文件。

谢谢!

【问题讨论】:

  • 当需要Main 组件时,您可以尝试添加.jsx 扩展
  • 我试过了,同样的问题...
  • 也许你需要在 Menu.jsx 中的 Link 周围添加大括号:import { Link } from 'react-router'

标签: reactjs


【解决方案1】:

在我看来,问题出在Menu.jsx 文件中从react-router 导入的Link 上。应该是这样的:

import { Link } from 'react-router'

export default class Menu extends Component {

请注意{}。 React 路由器导出一个带有 Link 键的对象。

在第二个文件中,您的导入看起来不错:

import { Router, Route, Link, browserHistory } from 'react-router'

这就解释了为什么当您在其中粘贴 Menu 类时它会起作用。

这里的提示是错误消息:

Check the render method of Menu.

因此,您可以确定 Menu 类正在加载,并且错误出现在您的渲染函数中。 如果未找到菜单文件,您将收到一条消息,指出菜单未定义或类似的东西。

【讨论】:

    猜你喜欢
    • 2014-12-31
    • 2021-09-01
    • 2018-12-24
    • 2021-07-09
    • 2020-05-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多