简体   繁体   中英

curly braces in es6 and react

I'm starting to learn react and es6 . I saw some curly braces in the import part.

import React,{Component} from 'react';

I noticed that curly braces in this code is to import those named export.

But I also saw some code in the JSX part,like:

render() {
  return (
    <div>
      <h1>Hello,wrold!</h1>
      <h2>It is {new Date().toLocaleTimeString()}</h2>
    </div>
  );
}

I am confused,does this curly braces has nothing to do with es6 syntax? or they have some kind of relation?

When we import something, we need to keep this in mind. If a component or module is exported with default keyword, you don't need to use curly braces but if it is exported without default keyword you need to use curly braces.

ex:

export class Main extends Component{}

when you are importing this component you need to import like this.

import {Main} from 'filename';

But when you create a component and export it with default keyword, you don't need to use curly braces.

ex:

export default class Main extends Component{}

you can import it like this

import Main from 'filename';

And in case of component or module body, we use curly braces to integrate JSX and javascript code.

To "insert JSX/ES code inside the HTML"

The part in the curly braces are processed like javascript code and their result is returned and inserted between the "It is" and "</h2"

The ES6 syntax

import React, {Component} from 'react';

Is an example of the syntax used to import ES6 modules - not to confuse with object destructuring. These are not related but are often confused as imports mimics shallow destructuring.

The JSX syntax

<h2>It is {new Date().toLocaleTimeString()}</h2>

Tells the JSX compiler to interpret whatever is inside the curly braces as javascript instead of text.

Neither the ES6 Import syntax, object destructuring, nor JSX curly braces are related.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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