首页 > 解决方案 > 我无法将任何文件导入到我的 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 文件。

标签: javascriptreactjs

解决方案


完全客户端 React 的设置说明不适用于导入。这种格式的限制是如此之大,以至于我认为 React 网站甚至建议将这种方法作为快速入门,这对新开发人员造成了严重的伤害。

遵循Create a New React App页面中的建议:

本页描述了一些流行的 React 工具链,它们可以帮助完成以下任务:

  • 缩放到许多文件和组件
  • 使用来自 npm 的第三方库。
  • 及早发现常见错误。
  • 在开发中实时编辑 CSS 和 JS。
  • 优化生产的输出。

使用create-react-app

或者,您可能要考虑使用 parcel提供更简单的工具链(但不那么常见且文档不完整)。


推荐阅读