javascript - 我无法将任何文件导入到我的 javascript 文件中
问题描述
我已经向现有项目添加了一个 React,如下所示:https ://reactjs.org/docs/add-react-to-a-website.html 我想将我的组件拆分成更小的组件,但事实证明我无法将任何文件导入我的 js 文件 (.js .css)。当我添加导入语句时,此文件中的整个代码都不起作用。我的主要组件 questions.js:
import RatingScale from "./ratingScale";
import "./style.css"
var questions = JSON.parse(document.getElementById("mydiv").dataset.questions);
class Question extends React.Component {
constructor(props) {
super(props);
}
render() {
return (
<div className="question">
<p>{this.props.content}</p>
<p>{this.props.id}</p>
<RatingScale />
</div>
);
}
}
ReactDOM.render(
<Question content={questions[0].question_text} />,
document.querySelector("#question1")
);
ReactDOM.render(
<Question content={questions[1].question_text} />,
document.querySelector("#question2")
);
ReactDOM.render(
<Question content="Pytanie 3" />,
document.querySelector("#question3")
);
ratingScale.js:
class RatingScale extends React.Component {
constructor(props) {
super(props);
}
render() {
return (
<div className="rating_scale">
<form>
<label>
<input type="radio" name="rad" value="1" />
<span>1</span>
</label>
<label>
<input type="radio" name="rad" value="2" />
<span>2</span>
</label>
<label>
<input type="radio" name="rad" value="3" />
<span>3</span>
</label>
<label>
<input type="radio" name="rad" value="4" />
<span>4</span>
</label>
<label>
<input type="radio" name="rad" value="5" />
<span>5</span>
</label>
</form>
</div>
);
}
}
export default RatingScale;
代码编译但在控制台中我有:
ReferenceError: Can't find variable: require
当我删除导入时,它可以正常工作。此外,当我输入 js 文件的名称时,它会看到它,但它没有 css 文件。
解决方案
完全客户端 React 的设置说明不适用于导入。这种格式的限制是如此之大,以至于我认为 React 网站甚至建议将这种方法作为快速入门,这对新开发人员造成了严重的伤害。
遵循Create a New React App页面中的建议:
本页描述了一些流行的 React 工具链,它们可以帮助完成以下任务:
- 缩放到许多文件和组件。
- 使用来自 npm 的第三方库。
- 及早发现常见错误。
- 在开发中实时编辑 CSS 和 JS。
- 优化生产的输出。
或者,您可能要考虑使用 parcel提供更简单的工具链(但不那么常见且文档不完整)。
推荐阅读
- jquery - JavaScript 客户端验证与 Laravel 服务器端验证
- node.js - npm 命令不适用于 vscode 终端
- php - 将 phpmyadmin 中的这段代码翻译成 laravel
- python - 如何按嵌套列表的第二列对元组列表进行排序?
- networking - 还原默认 vmware 后未创建桥接适配器
- c# - C# 解析 HTML 帖子数据
- javafx - 用于用户验证的 javafx 程序。添加用户程序效果很好。登录程序有运行时错误。尝试了很多解决方案,需要帮助
- python - 有没有办法让python脚本用旧文件替换新文件
- slider - 如何强制两个 jupyter 滑块相互交互(非常重要)?“标签”可用于处理程序吗?
- r - 如何在 R 中使用增量变量在 for 循环中定义函数?