01React JSX

7/28/2022 React

# React中JSX的使用

# 0.JSX是什么

React.createElement(component, props, ...children)的语法糖

React.createElement(
  "div" /* type */,
  { id: "container" } /* props */,
  "hello" /* children */
);
1
2
3
4
5
const element = <h1>Hello, world!</h1>;
1

在js中使用标记语言,是js的语法扩展,能够很好的描述UI的交互本质,具有js的全部功能,能够生成react元素

# 1.为什么使用JSX

JSX更加直观,并且React认为渲染逻辑本质上和其他UI逻辑内在耦合,React中将标记和逻辑共同存放在组件的松散耦合单元之中。

# 3.JSX基础

# 1.嵌入表达式

{}中可以放置任何js表达式,也可以用函数返回的表达式,将JSX放入()中避免自动插入分号 (opens new window)

const name = 'Josh Perez';
const element = <h1>Hello, {name}</h1>;
1
2
function formatName(user) {
  return user.firstName + ' ' + user.lastName;
}

const user = {
  firstName: 'Harper',
  lastName: 'Perez'
};

const element = (
  <h1>
    Hello, {formatName(user)}!
  </h1>
);
1
2
3
4
5
6
7
8
9
10
11
12
13
14

# 2.JSX也是一个表达式

在编译之后,JSX 表达式会被转为普通 JavaScript 函数调用,并且对其取值后得到 JavaScript 对象。

你可以将JSX赋值给变量,当参数、从函数中返回,都是可以的

function getGreeting(user) {
  if (user) {
    return <h1>Hello, {formatName(user)}!</h1>;
  }
  return <h1>Hello, Stranger.</h1>;
}
1
2
3
4
5
6

# 3.JSX中指定属性

可以用引号表示字符串字面量,也可以用{}插入js表达式,大括号外面不要加入表达式,属性用小驼峰命名className

const element = <a href="https://www.reactjs.org"> link </a>
const element = <img src={user.avatarUrl}></img
1
2

# 4.JSX指定子元素

标签中没有内容可以自闭合,可以包含很多子元素,跟HTML类似

# 5.JSX防止注入攻击

const title = response.potentiallyMaliciousInput;
// 直接使用是安全的:
const element = <h1>{title}</h1>;
1
2
3

React DOM 在渲染所有输入内容之前,默认会进行转义 (opens new window)。它可以确保在你的应用中,永远不会注入那些并非自己明确编写的内容。所有的内容在渲染之前都被转换成了字符串。这样可以有效地防止 XSS(cross-site-scripting, 跨站脚本) (opens new window)攻击。

# 6.JSX表示对象

Babel 会把 JSX 转译成一个名为 React.createElement() 函数调用。

const element = (
  <h1 className="greeting">
    Hello, world!
  </h1>
);

const element = React.createElement(
  'h1',
  {className: 'greeting'},
  'Hello, world!'
);

// 注意:这是简化过的结构
const element = {
  type: 'h1',
  props: {
    className: 'greeting',
    children: 'Hello, world!'
  }
};
这些对象被称为 “React 元素”。它们描述了你希望在屏幕上看到的内容。React 通过读取这些对象,然后使用它们来构建 DOM 以及保持随时更新。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21

# 7.使用.语法

在 JSX 中,你也可以使用点语法来引用一个 React 组件。当你在一个模块中导出许多 React 组件时,这会非常方便。例如,如果 MyComponents.DatePicker 是一个组件,你可以在 JSX 中直接使用:

import React from 'react';

const MyComponents = {
  DatePicker: function DatePicker(props) {
    return <div>Imagine a {props.color} datepicker here.</div>;
  }
}

function BlueDatePicker() {
  return <MyComponents.DatePicker color="blue" />;
}
1
2
3
4
5
6
7
8
9
10
11

以小写字母开头的元素代表一个 HTML 内置组件,比如 <div> 或者 <span> 会生成相应的字符串 'div' 或者 'span' 传递给 React.createElement(作为参数)。大写字母开头的元素则对应着在 JavaScript 引入或自定义的组件,如 <Foo /> 会编译为 React.createElement(Foo)

# 8.运行时选择类型

你不能将通用表达式作为 React 元素类型。如果你想通过通用表达式来(动态)决定元素类型,你需要首先将它赋值给大写字母开头的变量。这通常用于根据 prop 来渲染不同组件的情况下:

import React from 'react';
import { PhotoStory, VideoStory } from './stories';

const components = {
  photo: PhotoStory,
  video: VideoStory
};

function Story(props) {
  // 错误!JSX 类型不能是一个表达式。
  return <components[props.storyType] story={props.story} />;
}
1
2
3
4
5
6
7
8
9
10
11
12

要解决这个问题, 需要首先将类型赋值给一个大写字母开头的变量:

import React from 'react';
import { PhotoStory, VideoStory } from './stories';

const components = {
  photo: PhotoStory,
  video: VideoStory
};

function Story(props) {
  // 正确!JSX 类型可以是大写字母开头的变量。
  const SpecificStory = components[props.storyType];
  return <SpecificStory story={props.story} />;
}
1
2
3
4
5
6
7
8
9
10
11
12
13

# 4.JSX中的props

# 1.表达式作为Props

<MyComponent foo={1 + 2 + 3 + 4} />
1

if 语句以及 for 循环不是 JavaScript 表达式,所以不能在 JSX 中直接使用。但是,你可以用在 JSX 以外的代码中。比如:

function NumberDescriber(props) {
  let description;
  if (props.number % 2 == 0) {
    description = <strong>even</strong>;
  } else {
    description = <i>odd</i>;
  }
  return <div>{props.number} is an {description} number</div>;
}
1
2
3
4
5
6
7
8
9

# 2.字符串字面量

等价

<MyComponent message="hello world" />
<MyComponent message={'hello world'} />
1
2

如果你没给 prop 赋值,它的默认值是 true。以下两个 JSX 表达式是等价的:

<MyTextBox autocomplete />
<MyTextBox autocomplete={true} />
1
2

# 3.属性展开

function App1() {
  return <Greeting firstName="Ben" lastName="Hector" />;
}

function App2() {
  const props = {firstName: 'Ben', lastName: 'Hector'};
  return <Greeting {...props} />;
}
1
2
3
4
5
6
7
8

你还可以选择只保留当前组件需要接收的 props,并使用展开运算符将其他 props 传递下去。

const Button = props => {
  const { kind, ...other } = props;
  const className = kind === "primary" ? "PrimaryButton" : "SecondaryButton";
  return <button className={className} {...other} />;
};

const App = () => {
  return (
    <div>
      <Button kind="primary" onClick={() => console.log("clicked!")}>
        Hello World!
      </Button>
    </div>
  );
};
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15

在上述例子中,kind 的 prop 会被安全的保留,它将不会被传递给 DOM 中的 <button> 元素。 所有其他的 props 会通过 ...other 对象传递,使得这个组件的应用可以非常灵活。你可以看到它传递了一个 onClickchildren 属性。

# 5.JSX中的子元素

# 1.字符串

包含在开始和结束标签之间的 JSX 表达式内容将作为特定属性 props.children 传递给外层组件。有几种不同的方法来传递子元素:

<MyComponent>Hello world!</MyComponent>
1

JSX 会移除行首尾的空格以及空行。与标签相邻的空行均会被删除,文本字符串之间的新行会被压缩为一个空格。因此以下的几种方式都是等价的:

<div>Hello World</div>

<div>
  Hello World
</div>

<div>
  Hello
  World
</div>

<div>

  Hello World
</div>

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16

React 组件也能够返回存储在数组中的一组元素:

render() {
  // 不需要用额外的元素包裹列表元素!
  return [
    // 不要忘记设置 key :)
    <li key="A">First item</li>,
    <li key="B">Second item</li>,
    <li key="C">Third item</li>,
  ];
}
1
2
3
4
5
6
7
8
9

# 2.表达式

JavaScript 表达式可以被包裹在 {} 中作为子元素。例如,以下表达式是等价的:

<MyComponent>foo</MyComponent>
<MyComponent>{'foo'}</MyComponent>
1
2

这对于展示任意长度的列表非常有用。例如,渲染 HTML 列表:

function Item(props) {
  return <li>{props.message}</li>;
}

function TodoList() {
  const todos = ['finish doc', 'submit pr', 'nag dan to review'];
  return (
    <ul>
      {todos.map((message) => <Item key={message} message={message} />)}
    </ul>
  );
}
1
2
3
4
5
6
7
8
9
10
11
12

# 3.函数

通常,JSX 中的 JavaScript 表达式将会被计算为字符串、React 元素或者是列表。不过,props.children 和其他 prop 一样,它可以传递任意类型的数据,而不仅仅是 React 已知的可渲染类型。例如,如果你有一个自定义组件,你可以把回调函数作为 props.children 进行传递:

// 调用子元素回调 numTimes 次,来重复生成组件
function Repeat(props) {
  let items = [];
  for (let i = 0; i < props.numTimes; i++) {
    items.push(props.children(i));
  }
  return <div>{items}</div>;
}

function ListOfTenThings() {
  return (
    <Repeat numTimes={10}>
      {(index) => <div key={index}>This is item {index} in the list</div>}
    </Repeat>
  );
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16

# 4.布尔类型、Null 以及 Undefined 将会忽略

false, null, undefined, and true 是合法的子元素。但它们并不会被渲染。以下的 JSX 表达式渲染结果相同:

<div />

<div></div>

<div>{false}</div>

<div>{null}</div>

<div>{undefined}</div>

<div>{true}</div>
1
2
3
4
5
6
7
8
9
10
11

这有助于依据特定条件来渲染其他的 React 元素。例如,在以下 JSX 中,仅当 showHeadertrue 时,才会渲染 <Header /> 组件:

<div>
  {showHeader && <Header />}
  <Content />
</div>
1
2
3
4

值得注意的是有一些 “falsy” 值 (opens new window),如数字 0,仍然会被 React 渲染。例如,以下代码并不会像你预期那样工作,因为当 props.messages 是空数组时,将会渲染为数字 0

<div>
  {props.messages.length &&
    <MessageList messages={props.messages} />
  }
</div>
1
2
3
4
5

要解决这个问题,确保 && 之前的表达式总是布尔值:

<div>
  {props.messages.length > 0 &&
    <MessageList messages={props.messages} />
  }
</div>
1
2
3
4
5

反之,如果你想渲染 falsetruenullundefined 等值,你需要先将它们转换为字符串 (opens new window)

<div>
  My JavaScript variable is {String(myVariable)}.
</div>
1
2
3