React.Children提供了處理this.props.children的工具,this.props.children能夠任何數據(組件、字符串、函數等等)。React.children有5個方法:React.Children.map(),React.Children.forEach()、React.Children.count()、React.Children.only()、React.Children.toArray(),一般與React.cloneElement()結合使用來操做this.props.children。react
React.Children.map()數組
React.Children.map()有些相似Array.prototype.map()。若是children是數組則此方法返回一個數組,若是是null或undefined則返回null或undefined。第一參數是children,即示例中的Father組件裏的'hello world!'和() => <p>2333</p>函數。第二個參數是fucntion,function的參數第一個是遍歷的每一項,第二個是對應的索引。
function Father({children}) {
return(
<div>
{React.Children.map(children, (child, index) => {
...
})}
</div>
)
}
<Father>
hello world!
{() => <p>2333</p>}
</Father>
React.Children.forEach()
跟React.Children.map()同樣,區別在於無返回。
React.Children.count()
React.Children.count()用來計數,返回child個數。不要用children.length來計數,若是Father組件裏只有'hello world!'會返回12,顯然是錯誤的結果。
function Father({children}) {
return(
<div>
{React.Children.count(children)}
</div>
)
}
<Father>
hello world!
{() => <p>2333</p>}
</Father>
React.Children.only()
驗證children裏只有惟一的孩子並返回他。不然這個方法拋出一個錯誤。
function Father({children}) {
return(
<div>
{React.Children.only(children)}
</div>
)
}
<Father>
hello world!
</Father>
React.Children.toArray()
將children轉換成Array,對children排序時須要使用
function Father({children}) { let children1 = React.Children.toArray(children); return( <div> {children1.sort().join(' ')} </div> ) } <Father> {'ccc'} {'aaa'} {'bbb'} </Father>
//渲染結果: aaa bbb ccc
若是不用React.Children.toArray()方法,直接寫children.sort()就會報錯
Example:less
例若有這樣的需求,完成一個操做須要3個步驟,每完成一個步驟,對應的指示燈就會點亮。dom
index.jsx函數
import * as React from 'react';
import * as ReactDOM from 'react-dom';
import {Steps, Step} from './Steps';
function App() {
return (
<div>
<Steps currentStep={1}> //完成相應的步驟,改變currentStep的值。如,完成第一步currentStep賦值爲1,完成第二部賦值爲2
<Step />
<Step />
<Step />
</Steps>
</div>
);
}
ReactDOM.render(<App />, document.getElementById('root'));
Steps.jsx工具
import * as React from 'react';
import './step.less';
function Steps({currentStep, children}) {
return (
<div>
{React.Children.map(children, (child, index) => {
return React.cloneElement(child, {
index: index,
currentStep: currentStep
});
})}
</div>
);
}
function Step({index, currentStep}: any) {
return <div className={`indicator${currentStep >= index + 1 ? ' active' : ''}`} />;
}
export {Steps, Step};
steps.lessthis
.indicator { display: inline-block; width: 100px; height: 20px; margin-right: 10px; margin-top: 200px; background: #f3f3f3; &.active { background: orange; }