Refs 轉發
Fragments
React 中的一個常見模式是一個組件返回多個元素。Fragments 允許你將子列表分組,而無需向 DOM 添加額外節點。
class Columns extends React.Component {
render() {
return (
<div>
<td>Hello</td>
<td>World</td>
<div/>
);
}
}
//但你並不想渲染這個div 因爲他會破壞<table>的結構
render() {
return (
<React.Fragment>
<td>Hello</td>
<td>World</td>
</React.Fragment>
);
}
簡便寫法
//你可以像使用任何其他元素一樣使用 <> </>,除了它不支持 key 或屬性。
class Columns extends React.Component {
render() {
return (
<>
<td>Hello</td>
<td>World</td>
</>
);
}
}
key 是唯一可以傳遞給 Fragment 的屬性。未來我們可能會添加對其他屬性的支持,例如事件。
動機
高階組件
深入 JSX
實際上,JSX僅僅是React.createElement(compones,props,...children)
的語法糖
<MyButton color="blue" shadowSize={2}>
Click Me
</MyButton>
會編譯爲
React.createElement(
MyButton,
{color: 'blue', shadowSize: 2},
'Click Me'
)
可以去Babel編譯的結果去看
在 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" />;
}
可以選擇只保留當前組件需要接收的 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>
);
};
在上述例子中,kind 的 prop 會被安全的保留,它將不會被傳遞給 DOM 中的 元素。 所有其他的 props 會通過 …other 對象傳遞,使得這個組件的應用可以非常靈活。你可以看到它傳遞了一個 onClick 和 children 屬性。
JSX 中的子元素
包含在開始和結束標籤之間的 JSX 表達式內容將作爲特定屬性 props.children 傳遞給外層組件。有幾種不同的方法來傳遞子元素:
- 字符串字面量
你可以將字符串放在開始和結束標籤之間,此時 props.children 就只是該字符串。這對於很多內置的 HTML 元素很有用。例如:
<MyComponent>Hello world!</MyComponent>
這是一個合法的 JSX,MyComponent 中的 props.children 是一個簡單的未轉義字符串 “Hello world!”。
- JSX 子元素
- 函數作爲子元素
通常,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>
);
}
- 布爾類型、Null 以及 Undefined 將會忽略
false, null, undefined, and true 是合法的子元素。但它們並不會被渲染。以下的 JSX 表達式渲染結果相同:
<div />
<div></div>
<div>{false}</div>
<div>{null}</div>
<div>{undefined}</div>
<div>{true}</div>