无法在React Components中编写HTML [英] Can't write HTML in React Components

查看:39
本文介绍了无法在React Components中编写HTML的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用无节点的React或其他任何东西(我无法使用它,他们要求我在工作中以这种方式使用react ...对此我无能为力),我正在使用HTML文件并引用了不同的脚本.

I am using React without Node, or any other thing (I cannot use it, they asked me to do use react in this way in my job... nothing I can do about it), I am using a HTML file with references to different scripts.

因此,我设法使此代码起作用:

So, I managed to make this code work:

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8" />
    <title>Add React in One Minute</title>
    <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>
  </head>
  <body>
    <h1>HTML with multiple scripts using React.js</h1>
    <p>React.js without Node.js or any other thing</p>
    <p>React.js is loaded as script tags.</p>
    <div id="like_button_container"></div>
    <div id="like_button_container2"></div>
    <script src="like_button.js"></script>
    <script src="like_button2.js"></script>
  </body>
</html>

like_button.js:

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);

like_button2.js(是H1,不是按钮,仅用于测试):

like_button2.js (yes is an H1, not a button, just testing):

'use strict';

const f = React.createElement;

class LikeButton2 extends React.Component {
  constructor(props) {
    super(props);
    this.state = { liked: false };
  }

  render() {
    if (this.state.liked) {
      return 'You liked this.';
    }

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

const domContainer2 = document.querySelector('#like_button_container2');
ReactDOM.render(f(LikeButton2), domContainer2);

但是,我无法在组件返回中编写普通" HTML,导致它无法呈现,并且会给我一个错误:

However, I cannot write "normal" HTML in the return of the component, cause it won't render and will give me an error:

return f(
      <div>LOL</div>
    );

错误图片: https://i.imgur.com/VqxaQof.png

我该如何解决?在引号内写HTMl确实是有限制和可怕的.记住,不能使用Node或其他任何东西.

How can I solve this? is really limitating and awful to write HTMl within quotation marks... remember, cannot use Node or any other thing.

而且,¿我如何在同一个div中渲染所有内容?如果我尝试在同一个div上渲染这两个组件,那么它只会渲染第一个脚本,但是奇怪的是,一个脚本知道"另一个脚本的存在(例如,不能对变量使用相同的名称).

And also, ¿how can I render everything within the same div? If I try to render both components on the same div, it only renders the first script but the weird part is that one script is "aware" of the existence of the other (can't use same name for variables, for example).

预先感谢您,我真的为此受了苦.

Thank you in advance, I'm really suffering with this.

推荐答案

最大的问题是对 import 语句的支持仅限于更现代的浏览器.因此,如果要将元素保留在相同的 div id ="root" 中,则必须在同一文件中定义它们或使用第三方库.就是说, JSX 不是有效的HTML,因此您要么被迫强迫用户每次访问都将JSX转换为有效的JS (性能差,性能低,代码未优化以及浪费带宽),或者您想要

The biggest problem is that support for import statements is limited to more modern browsers. So if you want to keep the elements within the same div id="root", then you'll either have to define them within the same file or use a third-party library. That said, JSX isn't valid HTML, so you're either stuck forcing users to transpile the JSX into valid JS for every visit (bad -- slow performance, unoptimized code, and waste of bandwidth), or you're going to want to compile your JSX into a minified/optimized js file:

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8" />
    <title>Add React in One Minute</title>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
  </head>
  <body>
    <div id="root"></div>
    <script type="application/javascript">
    "use strict";function _instanceof(e,t){return null!=t&&"undefined"!=typeof Symbol&&t[Symbol.hasInstance]?!!t[Symbol.hasInstance](e):e instanceof t}function _typeof(e){return(_typeof="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e})(e)}function _classCallCheck(e,t){if(!_instanceof(e,t))throw new TypeError("Cannot call a class as a function")}function _defineProperties(e,t){for(var n=0;n<t.length;n++){var i=t[n];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable=!0),Object.defineProperty(e,i.key,i)}}function _createClass(e,t,n){return t&&_defineProperties(e.prototype,t),n&&_defineProperties(e,n),e}function _possibleConstructorReturn(e,t){return!t||"object"!==_typeof(t)&&"function"!=typeof t?_assertThisInitialized(e):t}function _getPrototypeOf(e){return(_getPrototypeOf=Object.setPrototypeOf?Object.getPrototypeOf:function(e){return e.__proto__||Object.getPrototypeOf(e)})(e)}function _assertThisInitialized(e){if(void 0===e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}function _inherits(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),t&&_setPrototypeOf(e,t)}function _setPrototypeOf(e,t){return(_setPrototypeOf=Object.setPrototypeOf||function(e,t){return e.__proto__=t,e})(e,t)}var H1LikeButton=function(e){function t(e){var n;return _classCallCheck(this,t),(n=_possibleConstructorReturn(this,_getPrototypeOf(t).call(this,e))).state={isLiked:!1},n.handleClick=n.handleClick.bind(_assertThisInitialized(n)),n}return _inherits(t,React.Component),_createClass(t,[{key:"handleClick",value:function(){this.setState(function(e){return{isLiked:!e.isLiked}})}},{key:"render",value:function(){return React.createElement(React.Fragment,null,this.state.isLiked&&React.createElement("p",null,"This is liked."),React.createElement("h1",{onClick:this.handleClick},!this.state.isLiked?"Like":"Dislike"))}}]),t}(),LikeButton=function(e){function t(e){var n;return _classCallCheck(this,t),(n=_possibleConstructorReturn(this,_getPrototypeOf(t).call(this,e))).state={isLiked:!1},n.handleClick=n.handleClick.bind(_assertThisInitialized(n)),n}return _inherits(t,React.Component),_createClass(t,[{key:"handleClick",value:function(){this.setState(function(e){return{isLiked:!e.isLiked}})}},{key:"render",value:function(){return React.createElement("div",null,this.state.isLiked&&React.createElement("p",null,"This is liked."),React.createElement("button",{onClick:this.handleClick},!this.state.isLiked?"Like":"Dislike"),React.createElement("br",null),React.createElement(H1LikeButton,null))}}]),t}();ReactDOM.render(React.createElement(LikeButton,null),document.getElementById("root"));
</script>
  </body>
</html>

因此...将所有内容编译到一个文件中,或者...您将必须使用

So... compile everything into a single file, or... you'll have to use a third party library that allows importing/exporting js files.

工作回购示例(使用 requirejs ):

Working repo example (using requirejs): https://github.com/mattcarlotta/standalone-requirejs-example

一些可以帮助您的工具:

Some tools to help you:

简而言之,不使用某种捆绑程序(webpack,汇总,gulp,parcel,browserify等)并不常见,因此尽管可以在开发中使用JSX,但是您仍然需要编译用于生产.由于无法使用节点和捆绑器,因此有望在整个开发/生产过程中受到阻碍.

In short, it's uncommon to not use some sort of bundler (webpack, rollup, gulp, parcel, browserify, ...etc), so while it's possible to work with JSX in development, you'll still want to compile it for production. By not being able to use node and a bundler, expect to be handicapped throughout development/production.

这篇关于无法在React Components中编写HTML的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆