JSX语法 and componentBasics

1. JSX语法介绍

1.1 what is JSX?

JSX is JavaScript XML 缩写, is Reactin用于describesUIstructure 语法scale. 它允许我们 in JavaScriptcodein直接writingclass似HTML code, 使componentstructure更清晰, Development更 high 效.

1.2 JSX basic语法

JSX basic语法 and HTMLclass似, 但 has 一些 important 区别:

import React from 'react';

function App() {
  return (
    <div className="App">
      <h1>Hello, JSX!</h1>
      <p>这 is a usingJSXwriting Reactcomponent. </p>
    </div>
  );
}

export default App;

1.3 JSX 编译

浏览器不能直接understandingJSX, 需要usingBabeletc.tool将JSX编译成普通 JavaScriptcode:

// JSXcode
const element = <h1>Hello, World!</h1>;

// 编译 after  JavaScriptcode
const element = React.createElement(
  'h1',
  null,
  'Hello, World!'
);

2. JSX语法规则

2.1 根元素

JSX表达式必须 has 一个根元素package裹:

// 正确
const element = (
  <div>
    <h1>标题</h1>
    <p>段落</p>
  </div>
);

// error - 没 has 根元素
const element = (
  <h1>标题</h1>
  <p>段落</p>
);

2.2 tag闭合

所 has tag必须闭合, including自闭合tag:

// 正确 - 普通tag闭合
<div> in 容</div>

// 正确 - 自闭合tag
<img src="image.jpg" alt="graph片" />

// error - tag未闭合
<div> in 容

2.3 驼峰命名

JSXinHTMLpropertyusing驼峰命名法:

// 正确 - using驼峰命名
<div className="container"></div>
<div onClick={handleClick}></div>
<input type="text" placeholder="请输入" />

// error - using short 横线命名
<div class="container"></div>
<div on-click={handleClick}></div>

2.4 JavaScript表达式

可以 in JSXinusingJavaScript表达式, 需要用 big 括号{}package裹:

const name = 'React';
const element = <h1>Hello, {name}!</h1>;

// 表达式
const a = 10;
const b = 20;
const element = <p>{a} + {b} = {a + b}</p>;

// function调用
function formatName(user) {
  return user.firstName + ' ' + user.lastName;
}

const user = { firstName: 'John', lastName: 'Doe' };
const element = <p>Hello, {formatName(user)}!</p>;

2.5 条件渲染

可以using三元运算符 or 逻辑 and (&&)for条件渲染:

// 三元运算符
const isLoggedIn = true;
const element = isLoggedIn ? 
  <p>欢迎回来!</p> : 
  <p>请login. </p>;

// 逻辑 and (&&)
const count = 5;
const element = <div>{count > 0 && <p> has {count}条 new message</p>}</div>;

2.6 list渲染

可以usingmap()methodforlist渲染, 需要 for 每个list项添加keyproperty:

const numbers = [1, 2, 3, 4, 5];
const listItems = numbers.map((number) =>
  <li key={number.toString()}>
    {number}
  </li>
);

const element = <ul>{listItems}</ul>;

3. ReactcomponentBasics

3.1 component concepts

component is Reactapplication basic构建块, 它将UI拆分 for 独立, 可复用 部分. 每个component负责渲染UI 一部分, 接收输入 (props) 并返回describesUI React元素.

3.2 functioncomponent

functioncomponent is 最basic componentclass型, 它 is a 接收props并返回React元素 function:

import React from 'react';

function Greeting(props) {
  return <h1>Hello, {props.name}!</h1>;
}

export default Greeting;

3.3 classcomponent

classcomponent is 基于ES6class component, 它inheritance自React.Component, 需要implementationrender()method:

import React, { Component } from 'react';

class Greeting extends Component {
  render() {
    return <h1>Hello, {this.props.name}!</h1>;
  }
}

export default Greeting;

3.4 component using

componentcreationcompletion after , 可以像usingHTMLtag一样using它:

import React from 'react';
import Greeting from './Greeting';

function App() {
  return (
    <div>
      <Greeting name="React" />
      <Greeting name="JavaScript" />
    </div>
  );
}

export default App;

4. component 嵌套 and 组合

4.1 component嵌套

component可以嵌套using, 一个component可以package含othercomponent:

import React from 'react';

function Header() {
  return <header><h1>网站标题</h1></header>;
}

function Content() {
  return <main><p>网站 in 容</p></main>;
}

function Footer() {
  return <footer><p>版权information</p></footer>;
}

function App() {
  return (
    <div>
      <Header />
      <Content />
      <Footer />
    </div>
  );
}

export default App;

4.2 component组合

component可以throughprops传递子component, implementationcomponent 组合:

import React from 'react';

function Container(props) {
  return (
    <div className="container">
      {props.children}
    </div>
  );
}

function App() {
  return (
    <Container>
      <h1>标题</h1>
      <p>这 is containers in   in 容. </p>
    </Container>
  );
}

export default App;

5. component Props

5.1 Props basicconcepts

Props is component 输入data, is component之间通信 主要方式. Props is 只读 , component不能modify自己 props.

5.2 Props 传递

Propsthroughproperty 方式传递给component:

import React from 'react';

function User(props) {
  return (
    <div className="user">
      <h3>{props.name}</h3>
      <p>年龄: {props.age}</p>
      <p>邮箱: {props.email}</p>
    </div>
  );
}

function App() {
  return (
    <div>
      <User 
        name="张三" 
        age={25} 
        email="zhangsan@example.com" 
      />
      <User 
        name="李四" 
        age={30} 
        email="lisi@example.com" 
      />
    </div>
  );
}

export default App;

5.3 Props 默认值

可以 for component props设置默认值:

import React from 'react';

function Greeting(props) {
  // 设置默认值
  const { name = 'Guest' } = props;
  return <h1>Hello, {name}!</h1>;
}

//  or 者using默认parameter
function Greeting({ name = 'Guest' }) {
  return <h1>Hello, {name}!</h1>;
}

function App() {
  return (
    <div>
      <Greeting name="React" /> // 输出: Hello, React!
      <Greeting /> // 输出: Hello, Guest!
    </div>
  );
}

export default App;

6. 练习

练习1: creationJSX元素

usingJSXcreation一个package含标题, 段落 and list React元素.

const element = (
  <div>
    <h1>我 爱 good </h1>
    <p>以 under  is 我喜欢 活动: </p>
    <ul>
      <li>阅读</li>
      <li>programming</li>
      <li>运动</li>
      <li>旅行</li>
    </ul>
  </div>
);

练习2: creationfunctioncomponent

creation一个名 for Product functioncomponent, 接收name, price and descriptionserving asprops, 并渲染产品information.

import React from 'react';

function Product(props) {
  return (
    <div className="product">
      <h2>{props.name}</h2>
      <p className="price">¥{props.price}</p>
      <p className="description">{props.description}</p>
    </div>
  );
}

export default Product;

// usingexample
<Product 
  name="Reacttutorial" 
  price={99} 
  description="全面LearningReactDevelopment tutorial" 
/>

练习3: 条件渲染 and list渲染

creation一个名 for UserList component, 接收一个usersarrayserving asprops, using条件渲染显示"没 has user" or userlist.

import React from 'react';

function UserList(props) {
  const { users } = props;
  
  return (
    <div className="user-list">
      <h2>userlist</h2>
      {users.length === 0 ? (
        <p>没 has user</p>
      ) : (
        <ul>
          {users.map((user) => (
            <li key={user.id}>{user.name}</li>
          ))}
        </ul>
      )}
    </div>
  );
}

export default UserList;

// usingexample
const users = [
  { id: 1, name: '张三' },
  { id: 2, name: '李四' },
  { id: 3, name: '王五' }
];

<UserList users={users} />