reactjs 类型“Element”不可分配给类型“ReactNode”,类型“Element”中缺少属性“children”,但类型“ReactPortal”中需要该属性. ts(2322)

izkcnapc  于 2023-10-17  发布在  React
关注(0)|答案(1)|浏览(1388)

我想通过使用react-bootstrap创建导航栏,我把下面的代码放在src\components\header.tsx中,它想把header作为组件:

  1. import Container from 'react-bootstrap/Container';
  2. import Nav from 'react-bootstrap/Nav';
  3. import Navbar from 'react-bootstrap/Navbar';
  4. import NavDropdown from 'react-bootstrap/NavDropdown';
  5. function BasicExample() {
  6. return (
  7. <Navbar expand="lg" className="bg-body-tertiary">
  8. <Container>
  9. <Navbar.Brand href="#home">React-Bootstrap</Navbar.Brand>
  10. <Navbar.Toggle aria-controls="basic-navbar-nav" />
  11. <Navbar.Collapse id="basic-navbar-nav">
  12. <Nav className="me-auto">
  13. <Nav.Link href="#home">Home</Nav.Link>
  14. <Nav.Link href="#link">Link</Nav.Link>
  15. <NavDropdown title="Dropdown" id="basic-nav-dropdown">
  16. <NavDropdown.Item href="#action/3.1">Action</NavDropdown.Item>
  17. <NavDropdown.Item href="#action/3.3">Something</NavDropdown.Item>
  18. </NavDropdown>
  19. </Nav>
  20. </Navbar.Collapse>
  21. </Container>
  22. </Navbar>
  23. );
  24. }
  25. export default BasicExample;

但它返回navbar.brand或container的错误

  1. Type 'Element' is not assignable to type 'ReactNode'.
  2. Property 'children' is missing in type 'Element' but required in type 'ReactPortal'.ts(2322)
  3. index.d.ts(207, 9): 'children' is declared here.
  4. index.d.ts(1466, 9): The expected type comes from property 'children' which is declared here on type 'IntrinsicAttributes & Omit<Omit<DetailedHTMLProps<HTMLAttributes<HTMLElement>, HTMLElement>, "ref"> & { ...; }, BsPrefixProps<...> & NavbarProps> & BsPrefixProps<...> & NavbarProps & { ...; }'

我能知道你的内心是怎么了吗

qybjjes1

qybjjes11#

我也有这个问题。只需将esModuleInterop添加到tsconfig.json文件中,或者如果存在,则按如下方式打开此属性:

  1. {
  2. "compilerOptions": {
  3. "module": "esnext",
  4. "target": "es5",
  5. "lib": ["es6", "dom"],
  6. "sourceMap": true,
  7. "allowJs": true,
  8. "jsx": "react-jsx",
  9. "moduleResolution": "node",
  10. "noImplicitAny": false,
  11. "esModuleInterop": true,
  12. },
  13. "include": ["src"]
  14. }

根据官方的打印文档
默认情况下(esModuleInterop为false或未设置),TypeScript将CommonJS/AMD/UMD模块视为类似于ES6模块。
如果您使用的是使用CommonJS或AMD模块的第三方库,强烈建议您启用此选项。

展开查看全部

相关问题