猿问

import 语句给出语法错误,指出“无法在模块外部使用 import 语句”

我是Web开发的新手,这只是我创建的一个简单的代码,用于测试我安装的新文本编辑器,我在尝试导入react时遇到了此错误,因为我遇到了一些其他错误,例如;类型错误: 无法读取未定义的属性“createElement”


请问,我该如何解决这个问题?导入语句有误吗?


import React, { Fragment } from 'react';

console.log("Testing");

var document;//made this declaration because I got a document undefined error

 document.createElement("p"):

const p = document.createElement("p")


p.innerHTML = "This is to test the javascript";

const body = document.querySelector("body");


body.insertBefore(p,body.childNode[-1]);

<!DOCTYPE html>

<html>

<head>

  <title>Testing vs code</title>

  <link rel="stylesheet" type="text/css" href="styles.css"/>

  

</head>


<body>

  <h1>Testing the vscode html preview package</h1>

  <h2>Hello</h2>

  <script type="module" src="js-prac.js"></script>

</body>

</html>


繁花不似锦
浏览 97回答 3
3回答

隔江千里

我知道你想用 React 创建一个简单的应用程序。我建议你先读一&nbsp;https://kentcdodds.com/blog/how-to-react,然后再读这个:https://reactjs.org/tutorial/tutorial.html可以通过在开始时导入脚本来创建 react 应用程序,但这不是构建 react 应用程序的推荐方法。完成上述帖子后,请在您选择的平台上找到您选择的好教程,无论是基于博客还是基于视频。我可以举出一些像udemy,前端大师,复数视觉,还有更多。

LEATH

看看 ReactJS 网站。你应该使用 Node 包管理器创建 React 应用程序 npx create-react-app appName或者应该将反应脚本链接到您的html<script src="https://unpkg.com/react@16/umd/react.development.js"></script>&nbsp;<script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>也不能重新定义文档对象。这将引用您的网页,您可以使用文档对象访问元素或 DOM(文档对象模型)。

犯罪嫌疑人X

根据 https://reactjs.org/docs/add-react-to-a-website.html,您需要在导入脚本之前将以下两行添加到HTML文件中:<script src="https://unpkg.com/react@16/umd/react.development.js" crossorigin></script>&nbsp;<script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js" crossorigin></script>我不确定模块加载是否会按照你想要的方式工作,而不使用像Create React App这样的东西。您可以删除导入语句,并且仍然可以在脚本中引用 React 和 ReactDOM。例如:'use strict';const e = React.createElement;class LikeButton extends React.Component {&nbsp; constructor(props) {&nbsp; &nbsp; super(props);&nbsp; &nbsp; this.state = { liked: false };&nbsp; }&nbsp; render() {&nbsp; &nbsp; if (this.state.liked) {&nbsp; &nbsp; &nbsp; return 'You liked comment number ' + this.props.commentID;&nbsp; &nbsp; }&nbsp; &nbsp; return e(&nbsp; &nbsp; &nbsp; 'button',&nbsp; &nbsp; &nbsp; { onClick: () => this.setState({ liked: true }) },&nbsp; &nbsp; &nbsp; 'Like'&nbsp; &nbsp; );&nbsp; }}// Find all DOM containers, and render Like buttons into them.document.querySelectorAll('.like_button_container')&nbsp; .forEach(domContainer => {&nbsp; &nbsp; // Read the comment ID from a data-* attribute.&nbsp; &nbsp; const commentID = parseInt(domContainer.dataset.commentid, 10);&nbsp; &nbsp; ReactDOM.render(&nbsp; &nbsp; &nbsp; e(LikeButton, { commentID: commentID }),&nbsp; &nbsp; &nbsp; domContainer&nbsp; &nbsp; );&nbsp; });
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答