为什么这不起作用(无节点反应)?

时间:2019-12-24 07:25:23

标签: javascript html reactjs

我正在努力使这项工作:

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8" />
    <title>Add React in One Minute</title>
  </head>
  <body>

    <h2>Add React in One Minute</h2>
    <p>This page demonstrates using React with no build tooling.</p>
    <p>React is loaded as a script tag.</p>

    <!-- We will put our React component inside this div. -->
    <div id="like_button_container"></div>

    <!-- Load React. -->
    <!-- Note: when deploying, replace "development.js" with "production.min.js". -->
    <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>

    <!-- Load our React component. -->
    <script src="like_button.js"></script>

  </body>
</html>

这是like_button.js:

'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 this.';
    }

    return e(
      'button',
      { onClick: () => this.setState({ liked: true }) },
      'Like'
    );
  }
}

const domContainer = document.querySelector('#like_button_container');
ReactDOM.render(e(LikeButton), domContainer);

但是该组件(按钮)没有出现,这是从此站点发出的:

https://reactjs.org/docs/add-react-to-a-website.html

请帮助我,就像它无法识别脚本一样。

2 个答案:

答案 0 :(得分:1)

这里的问题是您直接从硬盘驱动器将页面作为文件运行,which is preventing external scripts(例如react,react-dom)已从下载中下载。这意味着React从未下载且未定义,这反过来又破坏了like_button.js脚本。

相反,直接从硬盘驱动器运行HTML页面,请尝试通过服务器运行该页面-如果已安装节点,则可以通过以下方式安装基本的http server

npm install -g http-server

完成后,从包含html页面的目录中运行以下命令:

http-server

然后,控制台将在控制台中显示服务器的地址。在Web浏览器中导航到该地址将显示索引页面或目录列表。导航到正在开发的html页面,您应该会发现一切正常。

更新

或者,如果您使用的是基于铬的浏览器(并且无法安装node),则可以安装此浏览器扩展程序以在系统上运行本地网络服务器:

Web Server for Chrome

安装后,您可以从存储项目的硬盘驱动器上的目录挂载并启动服务器(基本上通过浏览器扩展运行),然后导航至http://127.0.0.1:8887来访问页面。 / p>

希望有帮助!

答案 1 :(得分:-1)

import React from "react";

您的完整代码可以正常工作。

"use strict";
import React from "react";
import ReactDOM from "react-dom";
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 this.";
    }

    return e(
      "button",
      { onClick: () => this.setState({ liked: true }) },
      "Like"
    );
  }
}
const domContainer = document.querySelector("#like_button_container");
ReactDOM.render(e(LikeButton), domContainer);

检查此项是否正常demo

相关问题