【问题标题】:Sample ReactJS from reactjs.org code not working with JSXreactjs.org 代码中的示例 ReactJS 不能与 JSX 一起使用
【发布时间】:2020-05-04 00:25:50
【问题描述】:

我正在尝试按照此链接中给出的代码示例:https://reactjs.org/docs/add-react-to-a-website.html#add-react-in-one-minute 将反应组件运行到现有的 HTML 页面中。

但是当我尝试用JSX 替换本机JavaScript 时,我收到了这个错误:

ReferenceError: e 未定义

我知道我需要用一些东西替换 e(LikeButton))。但没有提到渲染代码中要更新的内容。

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

    // Display a "Like" <button>
    return (
      <button onClick={() => this.setState({ liked: true })}>
        Like
      </button>
    );
  }
}

index.html:

<!-- 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>

<script src="https://unpkg.com/babel-standalone@6/babel.min.js"></script>
<!-- Load our React component. -->

<script src="{{ asset('theme_assets/js/react/likebutton.js') }}" type="text/babel"></script>

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

【问题讨论】:

  • 具体在哪里?但我认为它不会起作用,因为e 没有在任何地方定义。那么用什么代替e(...)

标签: javascript reactjs jsx babeljs


【解决方案1】:

替换

ReactDOM.render(e(LikeButton), domContainer);

ReactDOM.render(<LikeButton />, domContainer);

工作代码在这里 https://jsbin.com/wuqoluyovu/edit?html,console,output

【讨论】:

  • 工作..!但我需要将querySelector 2 行代码移动到组件中。但是为什么官方文档中缺少了这个最重要的一步呢?
  • 我同意官方文档中缺少这一点,但是,根据 API,它应该将 react 元素作为第一个参数传递。 reactjs.org/docs/react-dom.html#render
  • 该文档适用于首次实施者并尝试第一次使用 React 的人。那么不应该认为这个人是众所周知的反应并浏览了 API 文档。无论如何,谢谢...!
猜你喜欢
  • 2015-09-04
  • 2018-08-24
  • 2022-06-11
  • 1970-01-01
  • 1970-01-01
  • 2019-06-19
  • 2015-06-22
  • 2018-02-03
  • 2021-08-26
相关资源
最近更新 更多