gpt4 book ai didi

javascript - 导入自定义 React 组件时元素类型无效

转载 作者:行者123 更新时间:2023-12-01 00:57:41 25 4
gpt4 key购买 nike

我试图在我的 React 应用程序中渲染自定义导航栏,但收到无效类型错误。

我知道 React 中有默认的和命名的导入/导出,但是我将 CustomNavBar 类作为默认导出,并将其作为默认导入到 App.jsx 中。其他发帖者提到这可能是软件包版本的问题,但我不知道从哪里开始解决这个问题。

App.jsx:

import Button from 'react-bootstrap/Button';
import { BrowserRouter as Router, Route} from 'react-router-dom';
import Home from './components/Home';
import About from './components/About';
import Resume from './components/Resume';
import CustomNavBar from './components/CustomNavBar';
import './App.css';

function App() {
return (
<div className="App">
<Router>
<div>
<CustomNavBar />
<Route exact path = "/" component={Home} />
<Route path = "/about" component={About} />
<Route path = "/resume" component={Resume} />
</div>
</Router>

</div>
);
}

export default App;

当省略 CustomNavBar 组件时,代码正常运行。

CustomNavBar.jsx:

import React, { Component } from 'react'  
import { Navbar, Nav, NavItem } from 'react-bootstrap';
import { Link } from 'react-router-dom';


export default class CustomNavBar extends Component {
render() {
return (
<Navbar default collapseOnSelect>
<Navbar.Header>
<Navbar.Brand>
<Link to="/">Home</Link>
</Navbar.Brand>
<Navbar.Toggle />
</Navbar.Header>
<Navbar.Collapse>
<Nav pullRight>
<NavItem eventKey={1} componentClass={Link} to="/">
Home
</NavItem>
<NavItem eventKey={2} componentClass={Link} to="/about">
About
</NavItem>
<NavItem eventKey={3} componentClass={Link} to="/resume">
Resume
</NavItem>
</Nav>
</Navbar.Collapse>
</Navbar>
);
}
}

package.json:

{
"name": "my_site",
"version": "0.1.0",
"private": true,
"dependencies": {
"bootstrap": "^4.3.1",
"react": "^16.8.6",
"react-bootstrap": "^1.0.0-beta.8",
"react-dom": "^16.8.6",
"react-router": "^5.0.0",
"react-router-dom": "^4.4.0-beta.8",
"react-scripts": "3.0.1"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
},
"eslintConfig": {
"extends": "react-app"
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
}
}

错误:

元素类型无效:需要一个字符串(对于内置组件)或一个类/函数(对于复合组件),但得到:未定义。您可能忘记从定义它的文件中导出组件,或者您可能混淆了默认导入和命名导入。

检查CustomNavBar的渲染方法。

/****已解决****/ header 不再从 Bootstrap 导出,品牌和切换不应包含在 Bootstrap 4 的 div 中。

最佳答案

从react-bootstrap的文档来看,我认为它没有公开Navbar.Header。这可能是问题所在吗?我对 NavItem 有同样的预感。在我看来,它应该说Nav.Item

关于javascript - 导入自定义 React 组件时元素类型无效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56400799/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com