React版本:15.4.2
**翻譯:xiyoki **
從根本上說,JSX只是為React.createElement(component, props, ...children)
函數(shù)提供語法糖。JSX代碼:
<MyButton color="blue" shadowSize={2}>
Click Me
</MyButton>
編譯成:
React.createElement(
MyButton,
{color: 'blue', shadowSize: 2},
'Click Me'
)
如果沒有子代,也可以使用標記的自關閉形式。所以:
<div className="sidebar" />
編譯成:
React.createElement(
'div',
{className: 'sidebar'},
null
)
如果你想測試一些特定的JSX是如何轉換成Javascript,你可以試試在線Babel編譯器。
Specifying The React Element Type(指定React元素類型)
JSX標記的第一部分決定了React元素的類型。
大寫的類型表示JSX標簽指的是React組件。這些標簽被編譯為對命名變量的直接引用,因此如果使用JSX<Foo />
表達式,Foo
則必須在作用域中。
React Must Be in Scope(React必須在作用域中)
由于JSX編譯需調用React.createElement
,因此React
庫還必須始終在JSX代碼的作用域中。
例如,這兩個import在此代碼中是必需的,即使React
和CustomButton
不是從Javascript直接引用的:
import React from 'react';
import CustomButton from './CustomButton';
function WarningButton() {
// return React.createElement(CustomButton, {color: 'red'}, null);
return <CustomButton color="red" />;
}
如果你沒有使用Javascript捆綁器,并且將React作為一個script標簽進行添加,那么React已經作為全局React存在于作用域中。
Using Dot Notation for JSX Type(對JSX類型使用點符號)
你可以使用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" />;
}
User-Defined Components Must Be Capitalized(用戶自定義的組件必須大寫)
當元素類型以小寫字母開頭時,它指向類似于<div>
或<span>
的內置組件,并生成字符串'div'
或'span'
傳遞給React.createElement
。以大寫字母開頭的元素類型,如<Foo />
編譯到React.createElement(Foo)
,并且同JavaScript文件中已定義或已導入的組件相對應。
我們建議你使用大寫字母命名組件。如果你有一個以小寫字母開頭的組件,請在將其用于JSX之前將其分配給大寫的變量。
例如,此代碼不會按預期運行:
import React from 'react';
// Wrong! This is a component and should have been capitalized:
function hello(props) {
// Correct! This use of <div> is legitimate because div is a valid HTML tag:
return <div>Hello {props.toWhat}</div>;
}
function HelloWorld() {
// Wrong! React thinks <hello /> is an HTML tag because it's not capitalized:
return <hello toWhat="World" />;
}
為了解決這個問題,我們將重命名hello為Hello,并且在引用它的時候使用<Hello />
:
import React from 'react';
// Correct! This is a component and should be capitalized:
function Hello(props) {
// Correct! This use of <div> is legitimate because div is a valid HTML tag:
return <div>Hello {props.toWhat}</div>;
}
function HelloWorld() {
// Correct! React knows <Hello /> is a component because it's capitalized.
return <Hello toWhat="World" />;
}
Choosing the Type at Runtime(在運行時選擇類型)
不能將常規(guī)表達式用作React元素類型。如果你想使用一個通用表達式來表示元素的類型,只需先將它賦給一個大寫的變量。這通常出現(xiàn)在你想基于一個prop渲染一個不同的組件:
import React from 'react';
import { PhotoStory, VideoStory } from './stories';
const components = {
photo: PhotoStory,
video: VideoStory
};
function Story(props) {
// Wrong! JSX type can't be an expression.
return <components[props.storyType] story={props.story} />;
}
為了解決這個問題,我們將首先將類型指定為大寫變量:
import React from 'react';
import { PhotoStory, VideoStory } from './stories';
const components = {
photo: PhotoStory,
video: VideoStory
};
function Story(props) {
// Correct! JSX type can be a capitalized variable.
const SpecificStory = components[props.storyType];
return <SpecificStory story={props.story} />;
}
Props in JSX(JSX中的Props)
在JSX中指定prop有幾種不同的方法。
JavaScript Expressions(JavaScript表達式)
你可以傳遞任何JavaScript表達式作為props,用{}
包裹它。例如,在這個JSX中:
<MyComponent foo={1 + 2 + 3 + 4} />
對于MyComponent
的props.foo
的值將是10
,因為表達式1 + 2 + 3 + 4
被求值。
if
語句和for
循環(huán)不是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>;
}
String Literals(字符串字面量)
你可以傳遞一個字符串字面量作為prop。這兩個JSX表達式是等價的:
<MyComponent message="hello world" />
<MyComponent message={'hello world'} />
當你傳遞一個字符串字面量時,它的值是HTML-unescaped。所以這兩個JSX表達式是等價的:
<MyComponent message="<3" />
<MyComponent message={'<3'} />
此行為通常不相關。這里只提到完整性。
Props Default to "True"(Props默認為'True')
如果你傳遞一個prop沒有值,它默認為true
。
這兩個JSX表達式是等價的:
<MyTextBox autocomplete />
<MyTextBox autocomplete={true} />
一般來說,我們不建議使用這個,因為它會與** ES6 object shorthand(ES6對象速記)**混淆,{foo}
是{foo:foo}
的簡寫,而不是{foo:true}
的簡寫。這種行為只是存在,以便于它匹配HTML的行為。
Spread Attributes(擴展屬性)
如果你已經有一個props
對象,并且想要在JSX中傳遞它,你可以使用...
作為一個'spread'
運算符傳遞整個props對象。這兩個組件是等效的:
function App1() {
return <Greeting firstName="Ben" lastName="Hector" />;
}
function App2() {
const props = {firstName: 'Ben', lastName: 'Hector'};
return <Greeting {...props} />;
}
當構建通用容器時,擴展屬性可能很有用。然而它們也可以很容易地將大量的不相關props傳遞給不關心它們的組件,從而讓你的代碼凌亂。我們建議你謹慎使用此語法。
Children in JSX(JSX中的子級)
在包含開始標記和結束標記的JSX表達式中,這些標記之間的內容作為特殊的props傳遞:props.children
。有幾種不同的方式傳遞children:
String Literals(字符串字面量)
你可以在開始和結束標簽之間放置一個字符串,props.children
就是那個字符串。這對許多內置的HTML元素很有用。例如:
<MyComponent>Hello world!</MyComponent>
這是有效的JSX,MyComponent
中的props.children
將是簡單的"hello world!"
字符串。HTML是非轉義的,所以你通常可以像寫HTML那樣寫JSX:
<div>This is valid HTML & JSX at the same time.</div>
JSX刪除行的開始和結尾處的空格。它也刪除空白行。與標簽相鄰的新行被刪除;在字符串文字中間出現(xiàn)的新行被壓縮到一個空格中。所以這些都渲染同樣的事情:
<div>Hello World</div>
<div>
Hello World
</div>
<div>
Hello
World
</div>
<div>
Hello World
</div>
JSX Children(JSX子級)
你可以提供更多的JSX元素作為children。這對于渲染嵌套組件很有用:
<MyContainer>
<MyFirstComponent />
<MySecondComponent />
</MyContainer>
你可以混合不同類型的children,所以你可以將字符串字面量與JSX children一起使用。這是JSX的另一種方式,就像HTML一樣,所以這是有效的JSX和有效的HTML:
<div>
Here is a list:
<ul>
<li>Item 1</li>
<li>Item 2</li>
</ul>
</div>
React組件不能返回多個React元素,但是單個JSX表達式可以有多個子元素,因此如果你想要一個組件渲染多個元素,你可以將其封裝在像div
這樣的標簽中。
JavaScript Expressions(JavaScript 表達式)
你可以將任何JavaScript表達式作為子表達式傳遞,將其放在{}
中。例如,這些表達式是等價的:
<MyComponent>foo</MyComponent>
<MyComponent>{'foo'}</MyComponent>
這通常用于渲染任意長度的JSX表達式列表。例如,這將渲染一個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>
);
}
JavaScript 表達式可以與其他類型的children混合使用。這通常用于替換字符串模板:
function Hello(props) {
return <div>Hello {props.addressee}!</div>;
}
Functions as Children(子級為函數(shù))
通常,插入JSX中的JavaScript 表達式將被計算為一個字符串、一個React元素或由這些事物構成的一個列表。然而,props.children
的工作就像任何其他prop,因為它可以傳遞任何類型的數(shù)據,而不只是React知道如何渲染的數(shù)據。例如,如果你有自定義組件,你可以將回調函數(shù)作為props.children
:
// Calls the children callback numTimes to produce a repeated component
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>
);
}
傳給自定義組件的子項可以是任何東西,只要該組件在渲染之前將它們轉換為React可以理解的東西即可。這種用法不常見,但如果你想伸展JSX的能力,這種用法是可行的。
Booleans, Null, and Undefined Are Ignored(忽略Booleans, Null 和 Undefined)
false, null, undefined,
和true
是有效的children。它們根本不渲染。這些JSX表達式將渲染相同的東西:
<div />
<div></div>
<div>{false}</div>
<div>{null}</div>
<div>{undefined}</div>
<div>{true}</div>
這對于條件性地渲染React元素很有用。如果showHeader
為true
,這個JSX只渲染一個<Header>
:
<div>
{showHeader && <Header />}
<Content />
</div>
警告,一些假的值,如數(shù)字0,仍然由React渲染。例如,此代碼將不會像你預期的那樣工作,因為當props.messages
為空數(shù)組時,0將打印:
<div>
{props.messages.length &&
<MessageList messages={props.messages} />
}
</div>
要解決這個問題,請確保前面的&&表達式總是布爾值:
<div>
{props.messages.length > 0 &&
<MessageList messages={props.messages} />
}
</div>
相反,如果你想有一個類似false, null, undefined,
和true
的值出現(xiàn)在輸出中,首先,你必須把它轉化為字符串:
<div>
My JavaScript variable is {String(myVariable)}.
</div>
ADVANCED GUIDES
1.JSX In Depth
2.Typechecking With PropTypes
3.Refs and the DOM
4.Uncontrolled Components
5.Optimizing Performance
6.React Without ES6
7.React Without JSX
8.Reconciliation
9.Context
10.Web Components
11.Higher-Order Components