React.js 中深入瞭解 JSX


JSX 最終使用 createElement 方法建立 React 元素。

示例

<FormButton color="green" buttonSize={10}> Submit </FormButton>

將轉換為 -

React.createElement(
   FormButton,
   {color: 'green', buttonSize: 10},
   'Submit’
)

也可以新增自閉合標籤。

自定義 React 元素的首字母大寫

自定義 React 元素必須以大寫字母開頭命名,以便 React 區分 html 元素和 React 元素。

由於 Jsx 會轉換為 React.createElement,因此 React 庫必須在作用域內。為此,如果 jsx 需要使用,我們必須匯入 React。

使用點運算子訪問內部屬性

可以使用點運算子訪問元素的內部屬性。

示例

<FormComponent.TextArea size=”50”/>

執行時選擇 Jsx 元素的型別

一般表示式不能用於 React 元素的型別。首先我們必須將其分配給一個大寫變數,然後才能使用該變數。

示例

import React from 'react';
import { Cricket, Football } from './sportsTypes';
const components = {
   cricket: Cricket,
   football: Football
};
function Story(props) {
   // Below expression is wrong and cannot be used this way.
   return <components[props.cricket] player={props.name} />;
}

為了使其工作,我們將將其分配給一個大寫字母 -

import React from 'react';
import { Cricket, Football } from './sportsTypes';
const components = {
   cricket: Cricket,
   football: Football
};
function Story(props) {
   // Correct! JSX type can be a capitalized variable.
   const Sport = components[props.cricket];
   return <Sport player={props.name} />;
}

JSX 中的 Props 使用

Props 可以是 jsx 表示式

示例

<Player score={4+6+4} />

score 屬性將計算為 14

像 if、for 這樣的條件語句不能直接在 jsx 程式碼中使用,但它們可以單獨使用,並且它們的結果變數可以在 jsx 中使用。

Props 可以是字串字面量 -

<Player name={‘Steve’}/>

或者

<Player name=”Steve”/>

如果未提供,props 值將預設為 true。這僅僅是為了與 html 的預設行為相容。

示例

<Player isPlaying />

等於

<Player isPlaying={true} />

可以使用擴充套件運算子傳遞 props -

<Player {…props} />

JSX 中的子元素

開始標籤和結束標籤之間的內容是 jsx 子元素。

<Player> Steve </Player>

子元素也可以是 jsx 表示式或函式。如果 jsx 子元素屬於布林值 null、undefined 型別,則它們將被忽略。

更新於: 2019 年 9 月 5 日

251 次檢視

開啟您的 職業生涯

透過完成課程獲得認證

開始學習
廣告