导入 React 是如何让 JSX 作为 JS 处理的? [英] How does importing React allow JSX to be processed as JS?

查看:48
本文介绍了导入 React 是如何让 JSX 作为 JS 处理的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 create-react-app 学习 React,并且我了解如何使用 JSX 制作组件.例如一个简单的无状态组件是这样的:

I'm learning React with create-react-app and I understand how to make components with JSX. For example a simple stateless component is something like:

import React from 'react';

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

export default Widget;

所以导入 React 使用 createElement() 来转换看起来像 HTML 的 JSX (

{props.text}

),但该功能是如何应用的?我并不是明确地将 React 用于任何事情.如果在构建应用程序时进行某种编译,那么为什么需要导入 React?

So importing React uses createElement() for the conversion of the HTML-looking JSX (<h1>{props.text}</h1>), but how is that function applied? It's not like I am explicitly using React for anything. If there is some kind of compiling go on as the app is built, then why does React need to be imported?

推荐答案

首先,Babel 将 JSX 编译成常规的 Javascript,然后你的 React 导入,更准确地说是 React.createElement 函数来完成这项工作.这是您的代码的编译版本:

First, Babel compiles JSX into regular Javascript, then your React import, more accurately React.createElement function does the job. Here is the compiled version of your code:

"use strict";

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

这篇关于导入 React 是如何让 JSX 作为 JS 处理的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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