简体   繁体   English

导入 React 是如何让 JSX 作为 JS 处理的?

[英]How does importing React allow JSX to be processed as JS?

I'm learning React with create-react-app and I understand how to make components with JSX.我正在使用 create-react-app 学习 React,并且我了解如何使用 JSX 制作组件。 For example a simple stateless component is something like:例如一个简单的无状态组件是这样的:

import React from 'react';

const Widget = (props) => <h1>{props.text}</h1>

export default Widget;

So importing React uses createElement() for the conversion of the HTML-looking JSX ( <h1>{props.text}</h1> ), but how is that function applied?所以导入 React 使用createElement()来转换看起来像 HTML 的 JSX ( <h1>{props.text}</h1> ),但是这个函数是如何应用的呢? It's not like I am explicitly using React for anything.我并不是明确地将 React 用于任何事情。 If there is some kind of compiling go on as the app is built, then why does React need to be imported?如果在构建应用程序时进行某种编译,那么为什么需要导入 React?

First, Babel compiles JSX into regular Javascript, then your React import, more accurately React.createElement function does the job.首先,Babel 将 JSX 编译成常规的 Javascript,然后你的 React 导入,更准确地说是React.createElement函数来完成这项工作。 Here is the compiled version of your code:这是您的代码的编译版本:

"use strict";

var Widget = function Widget(props) {
  return React.createElement(
    "h1",
    null,
    props.text
  );
};

Importing React doesn't convert JSX into HTML;导入 React 不会将 JSX 转换为 HTML; Babel does that.巴别尔就是这样做的。 Babel is a JavaScript compiler. Babel是一个 JavaScript 编译器。

Babel effectively turns巴别塔有效转动

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

into进入

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

Read more in the React docs Add JSX to a Project .在 React 文档中阅读更多内容将 JSX 添加到项目

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

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