我正在尝试学习React,但我遇到了一个问题,在我用npm安装了React,React Dom和Bable之后,我无法导入这些库而不会出错。
import React from "react"
import ReactDOM from "react"
import Header from "./cp1-header"
import Footer from "./cp1-footer"
function Page() {
return(
<div>
<h1>Take a look at these Descriptions</h1>
<ol>
<li>Why I love React.js: </li>
<li>Thanks for watching </li>
<li>Make sure to like comment and subscribe </li>
</ol>
</div>
)
}
ReactDOM.render(<div><Header/><Page/><Footer/></div>, document.getElementById("root"));
错误是:无法在模块之外使用import语句。我尝试通过将package.json中的类型设置为module来修复此错误,但这并没有改变任何东西。我更新了我的import语句:
const React = require("react");
const ReactDOM = require("react-dom");
const Header = require("./cp1-header");
const Footer = require("./cp1-footer");
这导致了另一个错误,javascript无法识别我代码中的括号标记。我假设它无法理解Babel。我试图通过设置脚本type =“text/babel”并链接babel库来解决这个问题,但是抛出了另一个错误,指出require is not defined。
<html>
<head>
<link rel = "stylesheet" href = "cp1.css">
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
<script src="https://unpkg.com/babel-standalone@6/babel.min.js"></script>
</head>
<body>
<div id = "root"></div>
<script src = "cp1.js" type = "text/babel"></script>
</body>
</html>
我撤销了我的工作,感觉被卡住了。这是我目前的工作状态:
HTML
<html>
<head>
<link rel = "stylesheet" href = "cp1.css">
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
</head>
<body>
<div id = "root"></div>
<script src = "cp1.js"></script>
</body>
</html>
JavaScript
import React from "react"
import ReactDOM from "react"
import Header from "./cp1-header"
import Footer from "./cp1-footer"
function Page() {
return(
<div>
<h1>Take a look at these Descriptions</h1>
<ol>
<li>Why I love React.js: </li>
<li>Thanks for watching </li>
<li>Make sure to like comment and subscribe </li>
</ol>
</div>
)
}
ReactDOM.render(<div><Header/><Page/><Footer/></div>, document.getElementById("root"));
cp 1-页脚
import React from "react";
function Footer() {
return(
<div>"20ccc@Development Rights Reseved 2022</div>
)
}
export default Footer;
cp1-header
import React from "react";
function Header(){
return(
<nav className = "nav">
<img src = "https://www.sportsengineers.com/wp-content/uploads/2015/05/react-logo-570x570.png" className = "img"></img>
<ul className = "items">
<li>Home</li>
<li>Sign In</li>
<li>Sign Up</li>
</ul>
</nav>
)
}
export default Header
package json
{
"name": "react",
"version": "1.0.0",
"description": "",
"main": "cp1-footer.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"dependencies": {
"babel-preset-react": "^6.24.1",
"react": "^18.2.0",
"react-dom": "^18.2.0"
}
}
我如何使这个应用程序工作?我感到完全迷失了
1条答案
按热度按时间t3psigkw1#
我认为你可以通过进入package.json并添加
"type":"module"
作为属性来修复导入错误。package.json