我是一个新的web开发,这只是一个简单的代码,我创建了一个新的文本编辑器测试我安装,我得到了这个错误,而试图导入反应,因为我得到了一些其他的错误,如;TypeError.Cannot读取属性'createElement'的未定义。无法读取未定义的属性'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>
根据 https:/reactjs.orgdocsadd-react to a-website.html。,在导入脚本之前,你需要在你的HTML文件中添加这两行。
<script src="https://unpkg.com/react@16/umd/react.development.js" crossorigin></script>
<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 {
constructor(props) {
super(props);
this.state = { liked: false };
}
render() {
if (this.state.liked) {
return 'You liked comment number ' + this.props.commentID;
}
return e(
'button',
{ onClick: () => this.setState({ liked: true }) },
'Like'
);
}
}
// Find all DOM containers, and render Like buttons into them.
document.querySelectorAll('.like_button_container')
.forEach(domContainer => {
// Read the comment ID from a data-* attribute.
const commentID = parseInt(domContainer.dataset.commentid, 10);
ReactDOM.render(
e(LikeButton, { commentID: commentID }),
domContainer
);
});
我理解你想用React创建一个简单的应用程序。我建议你先阅读以下内容 https:/kentcdodds.comloghow-to-react。 还有这个。https:/reactjs.orgtutorialtutorial.html。
可以像你开始那样通过导入脚本来创建一个react应用,但这并不是推荐的构建react应用的方式。
当你看完上面的文章后,在你选择的平台上找一个好的教程,无论是博客还是基于视频的。我可以举出几个,比如udemy,frontend masters,pluralsight,还有很多。
请看一下 ReactJS网站.
你应该创建React应用程序使用 节点包管理器 npx create-react-app appName
或者应该将react脚本链接到你的html中
<script src="https://unpkg.com/react@16/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
同时你也不能重新定义文档对象。它引用了你的网页,你可以使用文档对象访问元素或DOM(文档对象模型)。