reactjs - วิธีการใช้ react-bootstrap ในโปรเจกต์ TypeScript
ฉันกำลังพยายามสร้างแถบการนำทางโดยใช้ react-bootstrap ฉันได้ติดตั้ง node-module ซึ่งเป็น "@types/react-bootstrap": "^0.32.11", และฉันต้องการใช้ในคอมโพเนนต์ hello.tsx ของฉัน แต่กลับแสดงข้อผิดพลาดในการคอมไพล์ Module not found: Error: Can't resolve 'react-bootstrap' in:\Query Express\Portal\src\components' ฉันไม่เข้าใจว่าทำไมมันถึงไปหาตัว react-bootstrap ในไดเรกทอรีคอมโพเนนต์
import * as React from "react";
import { Navbar, Nav, NavItem, NavDropdown, MenuItem } from "react-bootstrap";
export interface IHelloProps { compiler: string; framework: string; }
// 'helloProps' describes the shape of props.
// state is never set so we use the '{}' type.
export class Hello extends React.Component<IHelloProps, {}> {
render() {
return(
<div>
<Navbar inverse>
<Navbar.Header>
<Navbar.Brand>
<a href="#brand">React-Bootstrap</a>
</Navbar.Brand>
<Navbar.Toggle />
</Navbar.Header>
<Navbar.Collapse>
<Nav>
<NavItem eventKey={1} href="#">
Link
</NavItem>
<NavItem eventKey={2} href="#">
Link
</NavItem>
<NavDropdown eventKey={3} title="Dropdown" id="basic-nav-dropdown">
<MenuItem eventKey={3.1}>Action</MenuItem>
<MenuItem eventKey={3.2}>Another action</MenuItem>
<MenuItem eventKey={3.3}>Something else here</MenuItem>
<MenuItem divider />
<MenuItem eventKey={3.3}>Separated link</MenuItem>
</NavDropdown>
</Nav>
<Nav pullRight>
<NavItem eventKey={1} href="#">
Link Right
</NavItem>
<NavItem eventKey={2} href="#">
Link Right
</NavItem>
</Nav>
</Navbar.Collapse>
</Navbar>
<h1>Hello from {this.props.compiler} and {this.props.framework}!</h1>;
</div>
)}
}
index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
</head>
<body>
<div id="app"></div>
<!-- Main -->
<link href="./src/css/lib/_bootstrap.min.css" rel="stylesheet"></link>
<script src="./dist/main.bundle.js"></script>
<script src="./dist/nodeModules.bundle.js"></script>
</body>
</html>
คำตอบ #1
ในกรณีของฉัน ฉันแค่เพิ่มบรรทัดนี้ไปที่ไฟล์ index.tsx ของฉัน แล้วหลังจากนั้นมันก็ใช้งานได้ดี
import 'bootstrap/dist/css/bootstrap.min.css';
แต่ก่อนหน้านั้นคุณต้องติดตั้งไลบรารีโดยใช้คำสั่งนี้: npm i react-bootstrap bootstrap
คำตอบ #2
ข้อผิดพลาดนี้มักเกิดขึ้นเมื่อไม่พบโมดูลของโหนดหรืออาจติดตั้งไม่ถูกต้อง ดังนั้นในกรณีที่ไม่พบหรือไม่สามารถใช้งานได้ ให้รันคำสั่งต่อไปนี้ npm i react-bootstrap จากนั้นตรวจสอบให้แน่ใจว่ามันอยู่ในไฟล์ package.json ของคุณภายใต้ dependencies
ถ้าวิธีนี้ยังใช้ไม่ได้ ให้ลบไฟล์ package-lock.json และรัน npm i เพื่อติดตั้งแพ็กเกจทั้งหมดอีกครั้ง ตรวจสอบให้แน่ใจว่า react-bootstrap อยู่ใน dependencies ก่อนทำเช่นนั้น มิฉะนั้นให้ทำ npm i react-bootstrap ก่อน แล้วค่อย npm i