使用組件的目的就是通過構(gòu)建模塊化的組件,相互組合組件最后組裝成一個(gè)復(fù)雜的應(yīng)用。
在 React 組件中要包含其他組件作為子組件,只需要把組件當(dāng)作一個(gè) DOM 元素引入就可以了。
一個(gè)例子:一個(gè)顯示用戶頭像的組件 Avatar
包含兩個(gè)子組件 ProfilePic
顯示用戶頭像和 ProfileLink
顯示用戶鏈接:
import React from 'react';
import { render } from 'react-dom';
const ProfilePic = (props) => {
return (
<img src={'http://graph.facebook.com/' + props.username + '/picture'} />
);
}
const ProfileLink = (props) => {
return (
<a href={'http://www.facebook.com/' + props.username}>
{props.username}
</a>
);
}
const Avatar = (props) => {
return (
<div>
<ProfilePic username={props.username} />
<ProfileLink username={props.username} />
</div>
);
}
render(
<Avatar username="pwh" />,
document.getElementById('example')
);
通過 props
傳遞值。
如果組件中包含通過循環(huán)插入的子元素,為了保證重新渲染 UI
的時(shí)候能夠正確顯示這些子元素,每個(gè)元素都需要通過一個(gè)特殊的 key
屬性指定一個(gè)唯一值。具體原因見這里,為了內(nèi)部 diff 的效率。
key
必須直接在循環(huán)中設(shè)置:
const ListItemWrapper = (props) => <li>{props.data.text}</li>;
const MyComponent = (props) => {
return (
<ul>
{props.results.map((result) => {
return <ListItemWrapper key={result.id} data={result}/>;
})}
</ul>
);
}
你也可以用一個(gè) key
值作為屬性,子元素作為屬性值的對(duì)象字面量來顯示子元素列表,雖然這種用法的場(chǎng)景有限,參見Keyed Fragments,但是在這種情況下要注意生成的子元素重新渲染后在 DOM 中顯示的順序問題。
實(shí)際上瀏覽器在遍歷一個(gè)字面量對(duì)象的時(shí)候會(huì)保持順序一致,除非存在屬性值可以被轉(zhuǎn)換成整數(shù)值,這種屬性值會(huì)排序并放在其他屬性之前被遍歷到,所以為了防止這種情況發(fā)生,可以在構(gòu)建這個(gè)字面量的時(shí)候在
key
值前面加字符串前綴,比如:
render() {
var items = {};
this.props.results.forEach((result) => {
// If result.id can look like a number (consider short hashes), then
// object iteration order is not guaranteed. In this case, we add a prefix
// to ensure the keys are strings.
items['result-' + result.id] = <li>{result.text}</li>;
});
return (
<ol>
{items}
</ol>
);
}
this.props.children
組件標(biāo)簽里面包含的子元素會(huì)通過 props.children
傳遞進(jìn)來。
比如:
React.render(<Parent><Child /></Parent>, document.body);
React.render(<Parent><span>hello</span>{'world'}</Parent>, document.body);
HTML 元素會(huì)作為 React 組件對(duì)象、JS 表達(dá)式結(jié)果是一個(gè)文字節(jié)點(diǎn),都會(huì)存入 Parent
組件的 props.children
。
一般來說,可以直接將這個(gè)屬性作為父組件的子元素 render:
const Parent = (props) => <div>{props.children}</div>;
props.children
通常是一個(gè)組件對(duì)象的數(shù)組,但是當(dāng)只有一個(gè)子元素的時(shí)候,props.children
將是這個(gè)唯一的子元素,而不是數(shù)組了。
React.Children
提供了額外的方法方便操作這個(gè)屬性。