简体   繁体   English

React JSX无法识别?

[英]React JSX not being recognized?

I'm using these 2 CDN's to include React libraries in my project, however when I go to render some html using JSX onto the body of a HTML document it doesent recognize the JSX as JSX (I'm using chrome), and consequently throws up an error as it's reading the JSX as javascript. 我正在使用这两个CDN在我的项目中包括React库,但是当我去使用JSX在HTML文档的主体上渲染一些html时,它的确将JSX识别为JSX(我使用的是chrome),因此抛出正在以javascript读取JSX时出现错误。 Am I doing something wrong? 难道我做错了什么? Any help would be great :) CDN's: 任何帮助将是巨大的:) CDN:

<script crossorigin src="https://unpkg.com/react@16/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>

HTML: HTML:

<body>
   <div id="here"></div>  
</body>

React: 反应:

var React = require('react');
var ReactDOM = require('react-dom');
const text = <h1>Hello World</h1>;

ReactDOM.render(text, document.getElementById('here'));

You need a babel to use JSX . 您需要使用babel才能使用JSX

Two ways to add babel to your project are, babel添加到项目中的两种方法是:

  1. Add CDN for babel babel添加CDN
<script src="https://unpkg.com/babel-standalone@6/babel.min.js"></script>

Now you can use JSX in any <script> tag by adding type="text/babel" attribute to it. 现在,您可以通过JSX添加type="text/babel"属性在任何<script>标记中使用JSX

For example, 例如,

<script type="text/babel">
   const text = <h1>Hello, world!</h1>
   ReactDOM.render(
      text,
      document.getElementById('root')
   );
</script>

Demo 演示版

  1. Install babel using npm , 使用npm安装babel

From the docs 来自文档

Adding JSX to a project doesn't require complicated tools like a bundler or a development server. 将JSX添加到项目中并不需要诸如捆绑程序或开发服务器之类的复杂工具。 Essentially, adding JSX is a lot like adding a CSS preprocessor. 从本质上讲,添加JSX与添加CSS预处理器非常相似。 The only requirement is to have Node.js installed on your computer. 唯一的要求是在计算机上安装Node.js。

Go to your project folder in the terminal, and paste these two commands: 转到终端中的项目文件夹,并粘贴以下两个命令:

Step 1: Run npm init -y (If you get an "Invalid name" error when you run npm init -y, rename the project folder to only contain lowercase ASCII letters or hyphens (e.g. my-project), and try again.)

Step 2: Run npm install babel-cli@6 babel-preset-react-app@3

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM