react为什么要jsx_JSX到底是什么,为什么要使用它来构建React应用程序

react为什么要jsx

by Ryan Harris

瑞安·哈里斯(Ryan Harris)

JSX到底是什么,为什么要使用它来构建React应用程序 (What the heck is JSX and why you should use it to build your React apps)

As developers, we use a variety of tools and open source packages to make our jobs easier. Some of them are so widely used throughout the community that they seem native to JavaScript. But, they’re not, and they can fundamentally change how you write code on a daily basis.

作为开发人员,我们使用各种工具和开源软件包来简化我们的工作。 其中一些在整个社区中得到了如此广泛的使用,以至于它们似乎是JavaScript固有的。 但是,它们不是,它们可以从根本上改变您每天编写代码的方式。

One of these technologies that you are probably using already is JSX - a XML like syntax extension for JavaScript. Created by the team at Facebook, it is intended to simplify the developer experience. As the spec says, the rationale for creating JSX was:

您可能已经在使用的这些技术之一就是JSX- 类似于XMLJavaScript语法扩展 。 由Facebook团队创建,旨在简化开发人员体验。 如规范所述,创建JSX的理由是:

“…to define a concise and familiar syntax for defining tree structures with attributes.” ~ JSX Spec

“……定义简洁而熟悉的语法,以定义具有属性的树结构。” 〜JSX规格

Now, you’re probably saying to yourself, “Hey, Ryan, this sounds great, but get to the code already”, so here’s our first example.

现在,您可能对自己说:“嘿,Ryan,这听起来不错,但已经开始编写代码了 ”,所以这是我们的第一个示例。

const helloWorld = <h1>Hello, World!</h1>;

And that’s it!

就是这样!

The code snippet above looks familiar, but have you ever stopped to think about its power? JSX makes it so we can pass around tree structures composed of HTML or React elements as if they were standard JavaScript values.

上面的代码段看起来很熟悉,但是您有没有停下来思考一下它的功能? JSX做到了这一点,因此我们可以传递由HTML或React元素组成的树结构,就好像它们是标准JavaScript值一样。

While you don’t have to use JSX when writing React (or use React in order to try JSX), there’s no denying it is an important part of the React ecosystem, so let’s dive in and see what’s going on under the hood.

虽然您在编写React时不必使用JSX( 或使用React来尝试JSX ),但不可否认它是React生态系统的重要组成部分,因此让我们深入研究一下到底发生了什么。

JSX入门 (Getting started with JSX)

The first thing to note when using JSX syntax is that React must be in scope. This is due to how it gets compiled. Take this component for example:

使用JSX语法时要注意的第一件事是React必须在范围内。 这是由于它如何被编译。 以这个组件为例:

function Hello() {  return <h1>Hello, World!</h1>}

Behind the scenes, each element rendered by the Hello component is transpiled into to a React.createElement call.

在幕后,由Hello组件渲染的每个元素都将转换为React.createElement调用。

In this case:

在这种情况下:

function Hello() {  return React.createElement("h1", {}, "Hello, World!")}

The same is true for nested elements. The two examples below would ultimately render the same markup.

嵌套元素也是如此。 下面的两个示例最终将呈现相同的标记。

// Example 1: Using JSX syntaxfunction Nav() {  return (    <ul>      <li>Home</li>      <li>About</li>      <li>Portfolio</li>      <li>Contact</li>    </ul>  );}
// Example 2: Not using JSX syntaxfunction Nav() {  return (    React.createElement(      "ul",      {},      React.createElement("li", null, "Home"),      React.createElement("li", null, "About"),      React.createElement("li", null, "Portfolio"),      React.createElement("li", null, "Contact")    )  );}
React.createElement (React.createElement)

When React creates elements, it calls this method, which takes three arguments.

当React创建元素时,它将调用此方法,该方法带有三个参数。

  1. The element name

    元素名称
  2. An object representing the element’s props

    代表元素道具的对象
  3. An array of the element’s children

    元素的子元素数组

One thing to note here is that React interprets lowercase elements as HTML and Pascal case (ex. ThisIsPascalCase) elements as custom components. Because of this, the following examples would be interpreted differently.

这里要注意的一件事是,React将小写元素解释为HTML,而Pascal大小写(例如ThisIsPascalCase)元素则作为自定义组件。 因此,以下示例将有不同的解释。

// 1. HTML elementReact.createElement("div", null, "Some content text here")
// 2. React elementReact.createElement(Div, null, "Some content text here")

The first example would generate a <div> with the string "Some content text here" as its child. However, the second version would throw an error (unless, of course, a custom component &lt;Div /> was in scope) because <Div /> is undefined.

第一个示例将生成一个<d iv>,其tring "Some content texttring "Some content text此处的tring "Some content text ”作为其子级。 但是,第二个版本会引发错误(当然,除非自定义组件onent & lt; Div />是在sco pe) bec因为<Div />是未定义的。

JSX中的道具 (Props in JSX)

When working in React, your components often render children and need to pass them data in order for the children to render properly. These are called props.

在React中工作时,您的组件通常会渲染子代,并且需要传递它们数据才能使子代正确渲染。 这些被称为道具。

I like to think of React components as a group of friends. And what do friends do? They give each other props. Thankfully, JSX offers us a number of ways to do that.

我喜欢将React组件视为一群朋友。 朋友做什么? 他们互相提供道具 。 值得庆幸的是,JSX为我们提供了许多方法。

// 1. Props defaulted to true<User loggedIn />
// 2. String literals<User name="Jon Johnson" />
// 3. JavaScript expressions<User balance={5 + 5 + 10} />
// 4. Spread attributes<User preferences={...this.state} />

But beware! You cannot pass if statements or for loops as props because they are statements, not expressions.

但是要当心! 您不能将if语句或for循环作为道具传递,因为它们是语句,而不是表达式

JSX中的儿童 (Children in JSX)

As you are building your app, you eventually start having components render children. And then those components sometimes have to render children. And so on and so forth.

在构建应用程序时,最终将开始使组件呈现子级。 然后,这些组件有时不得不渲染子级。 等等等等。

Since JSX is meant to make it easy for us to reason about tree-like structures of elements, it makes all of this very easy. Basically, whatever elements a component returns become its children.

由于JSX旨在使我们易于推理元素的树状结构,因此使所有这些变得非常容易。 基本上,组件返回的任何元素都将成为其子代。

There are four ways to render child elements using JSX:

有四种方法可以使用JSX呈现子元素:

弦乐 (Strings)

This is the simplest example of JSX children. In the case below, React creates a <h1> HTML element with one child. The child, however, is not another HTML element, just a simple string.

这是JSX子级的最简单示例。 在以下情况下,React创建了一个带有一个子元素的< h1> HTML元素。 但是,该子项不是另一个HTML元素,而只是一个简单的字符串。

function AlertBanner() {  return (    <h1>Your bill is due in 2 days</h1>  )}
JSX元素 (JSX Elements)

This is probably the use case that new React developers would be most familiar with. In the component below, we’re returning an HTML child (the <header>), which has two children of its own &lt;Nav /> and &lt;ProfilePic /> both of which are custom defined JSX elements.

这可能是新的React开发人员最熟悉的用例。 在下面的组件中,我们返回一个HTML子元素( <head er>),它有两个子元素,分别是s own & lt; Na v /> and &l t; ProfilePic />,它们都是自定义的JSX元素。

function Header(props) {  return (    <header>      <Nav />      <ProfilePic />    </header>  )}
表达方式 (Expressions)

Expressions allow us to easily render elements in our UI that are the result of a JavaScript computation. A simple example of this would be basic addition.

表达式使我们能够轻松地在UI中呈现JavaScript计算的结果元素。 一个简单的例子就是基本加法。

Say we have a component called <BillFooter /> that renders information about a bill or receipt. Let’s assume it takes one prop called total that represents the pre-tax cost and another prop taxRate, which represents the applicable tax rate.

假设我们有一个名为<BillFooter />的组件,用于呈现有关账单或收据的信息。 让我们假设它需要一个道具Ç alled表示税前成本和另一个总prop t axRate,它代表的适用税率。

Using expressions, we can easily render out some useful information for our users!

使用表达式,我们可以轻松为用户呈现一些有用的信息!

function BillFooter(props) {  return (    <div>      <h5>Tax: {props.total * props.taxRate}</h5>      <h5>Total: {props.total + props.total * props.taxRate}</h5>    </div>  );}
功能 (Functions)

With functions, we can programmatically create elements and structures, which React will then render for us. This makes it easy to create multiple instances of a component or render repeated UI elements.

使用函数,我们可以以编程方式创建元素和结构,然后React将为我们呈现这些元素和结构。 这使创建一个组件的多个实例或呈现重复的UI元素变得容易。

As an example, let’s use JavaScript’s .map() function to create a navigation bar.

例如,让我们使用JavaScript的.map()函数创建导航栏。

// Array of page informationconst pages = [  {    id: 1,    text: "Home",    link: "/"  },  {    id: 2,    text: "Portfolio",    link: "/portfolio"  },  {    id: 3,    text: "Contact",    link: "/contact"  }];// Renders a <ul> with programmatically created <li> childrenfunction Nav() {  return (    <ul>      {pages.map(page => {        return (          <li key={page.id}>            <a href={page.link}>{page.text}</a>          </li>        );      })}    </ul>  );}

Now, if we want to add a new page to our site, all we need to do is add a new object to the pages array and React will take care of the rest!

现在,如果我们想向我们的站点添加一个新页面,我们要做的就是向pages数组添加一个新对象,React会处理剩下的一切!

Take note of the key prop. Our function returns an array of sibling elements, in this case <li>s, and React needs a way to keep track of which mounts, unmounts or updates. To do that, it relies on this unique identifier for each element.

注意 key 道具 。 我们的函数返回一个兄弟元素数组,在本例中为< li>,React需要一种跟踪哪个挂载,卸载或更新的方法。 为此,它依赖于每个元素的唯一标识符。

使用工具! (Use the tools!)

Sure, you can write React applications without JSX, but I’m not really sure why you’d want to.

当然,您可以在不使用JSX的情况下编写React应用程序,但是我不确定自己为什么要这么做。

The ability JSX gives us to pass around elements in JavaScript like they were first-class citizen lends itself well to working with the rest of the React ecosystem. So well, in fact, you may have been writing it every day and not even known it.

JSX的能力使我们能够像普通公民一样传递JavaScript中的元素,非常适合与React生态系统的其余部分一起工作。 很好,实际上,您可能每天都在写它,甚至都不知道。

Bottom line: just use JSX. You’ll be happy you did.

底线:只需使用JSX。 您会很高兴的。

翻译自: https://www.freecodecamp.org/news/what-the-heck-is-jsx-and-why-you-should-use-it-to-build-your-react-apps-1195cbd9dbc6/

react为什么要jsx

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值