babel和JSX有何关联或不同? [英] How babel and JSX related or differ?

查看:187
本文介绍了babel和JSX有何关联或不同?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习React JS,并且获得了有关JSX和babel的信息.但是我不清楚它们如何帮助React,以及它们之间或彼此之间的区别

I am learning on React JS and I have got information on JSX and babel. But I am not getting clarity on how these are helping React and how these or differ from each other

推荐答案

反应JS

在使用React构建应用程序时,您可以通过两种方式创建组件/视图

while building an app using React, you can create the components/views in two ways

  • 使用标准React对象和方法

  • using standard React object and methods

使用JSX

JSX

  • JSX是与React分离的一项技术,在构建React应用程序时是完全可选的,但是当您将JSX与React结合使用时,它使工作变得更加轻松.

让我们看看如何:

方法1:标准反应方式

(function() {

    var element = React.DOM.div({}, "Hello World");

    ReactDOM.render(element, document.getElementById("app"));

})();

可以在此链接找到该代码.

在这里,您只需要在页面中包含reactreact-dom库即可. 不需要任何其他内容.没有JSX,没有Babel.

Here, you just need to include the react and react-dom library to your page. Nothing else is required. No JSX, no Babel.

方法2:JSX方式

(function() {

    var HelloWorld = React.createClass({

        render : function() {
            return (
            <div> Hello World </div>
            );
        }
    });

    var element = React.createElement(HelloWorld, {});

    ReactDOM.render(element, document.getElementById("app"));

})();

可以在此链接找到该代码.

请注意此处的区别:<div> Hello World </div>用于JavaScript.这就是所谓的JSX语法.

Note the difference here: <div> Hello World </div> is used inside JavaScript. This is called JSX syntax.

现在,将JSX方法与普通JavaScript方法进行比较:

Now, compare the JSX approach with the vanilla JavaScript approach:

使用JSX,您可以像标准HTML一样内联添加更多 HTML类似元素,以创建视图层.

With JSX, You can add many more HTML like elements inline, just like standard HTML, to create the view layer.

在没有JSX的情况下,由于在JavaScript中创建HTML需要多层元素,因此代码可能会变得混乱.

Without JSX, the code can get messy because of the multiple layers of elements required to create HTML in JavaScript.

通天塔

现在的问题是,谁能理解JSX? 在这里,我们需要一个了解JSX并将其转换为可以在浏览器上运行的格式的编译器. Babel只是做这项工作.

Now the question is, who understands JSX?. Here We need a transpiler that understands JSX and converts it to a format that can run on browser. Babel does just this job.

转译

可以通过两种方式进行移植

Transpiling can be done two ways

  1. 基于浏览器/客户端的编译(仅用于开发) 目的)

  1. Browser based/client side transpiling (use only for development purpose)

  • 将此文件作为脚本标签
  • 在脚本标签上使用type="text/babel"来加载JSX
  • use type="text/babel" on your script tag which loads your JSX

这是示例代码

  1. 基于服务器的转码-例如通天塔

您可以使用不同的工具,例如webpack等.

You can use different tools like webpack etc.

这是一些示例代码.

希望这会有所帮助.

这篇关于babel和JSX有何关联或不同?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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