伙计们,我知道这个错误在这里已经问了很多遍了,但是我对此仍然感到非常困惑。因此,我尝试调用下面的Navbar组件
import React, { useState } from 'react';
import 'bootstrap/dist/css/bootstrap.min.css';
import {Collapse, Navbar, NavbarToggler, NavbarBrand, Nav, NavItem, NavLink} from 'reactstrap';
const [collapsed, setCollapsed] = useState(true);
const toggleNavbar = () => setCollapsed(!collapsed);
var mainNavbar1= () => {
return(
<div className = "mt-2">
<Navbar color="faded" light>
<NavbarBrand href="/" className="mr-auto">Welcome!</NavbarBrand>
<NavbarToggler onClick={toggleNavbar} className="mr-2" />
<Collapse isOpen={!collapsed} navbar>
<Nav navbar>
<NavItem>
<NavLink href="/components/">Home</NavLink>
</NavItem>
<NavItem>
<NavLink href="/components/">About</NavLink>
</NavItem>
<NavItem>
<NavLink href="/components/">Contact Me</NavLink>
</NavItem>
<NavItem>
<NavLink href="/components/">Components</NavLink>
</NavItem>
<NavItem>
<NavLink href="https://github.com/reactstrap/reactstrap">GitHub</NavLink>
</NavItem>
</Nav>
</Collapse>
</Navbar>
</div>
);
}
export default mainNavbar1;
在主要组件“ App”中,
import React, { useState } from 'react';
import 'bootstrap/dist/css/bootstrap.min.css';
import { Alert, Collapse, Navbar, NavbarToggler, NavbarBrand, Nav, NavItem, NavLink , Jumbotron,
Button, Container, Row, Col} from 'reactstrap';
import {mainNavbar1} from './mainNavbar';
var underDevelopmentAlert = () => {
alert("Page under development!!");
}
var App = () => {
return (
<mainNavbar1/>
)
}
我得到了上面的错误。我已经阅读了胡克斯的规则,并且仍然明白了这一点。我敢肯定我已经正确地遵循了所有步骤。 (Navbar组件直接从Reactstrap官方网站复制而来)
答案 0 :(得分:3)
首先,React组件必须以大写字母开头,没有例外。
第二,钩子不在组件内部,它们仅在组件所在的文件内部。您实际上需要将它们放入组件定义中。像这样:
const MainNavbar1 = () => {
const [collapsed, setCollapsed] = useState(true);
const toggleNavbar = () => setCollapsed(!collapsed);
return(...)
}
答案 1 :(得分:3)
钩子位置错误,应在组件函数中,但不能移出:
错误的方式:
const [collapsed, setCollapsed] = useState(true);
var MainNavbar1= () => {...}
正确的方法:
var MainNavbar1= () => {
const [collapsed, setCollapsed] = useState(true);
...
}