本教程操作環(huán)境:Windows10系統(tǒng)、react18.0.0版、Dell G3電腦。
【資料圖】
react children方法怎么用?
React.Children詳解
React.Children提供了處理this.props.children的工具,this.props.children可以任何數(shù)據(jù)(組件、字符串、函數(shù)等等)。React.children有5個(gè)方法:React.Children.map(),React.Children.forEach()、React.Children.count()、React.Children.only()、React.Children.toArray(),通常與React.cloneElement()結(jié)合使用來(lái)操作this.props.children。
React.Children.map()
React.Children.map()有些類(lèi)似Array.prototype.map()。如果children是數(shù)組則此方法返回一個(gè)數(shù)組,如果是null或undefined則返回null或undefined。第一參數(shù)是children,即示例中的Father組件里的"hello world!"和() => <p>2333</p>函數(shù)。第二個(gè)參數(shù)是fucntion,function的參數(shù)第一個(gè)是遍歷的每一項(xiàng),第二個(gè)是對(duì)應(yīng)的索引。
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()一樣,區(qū)別在于無(wú)返回。
React.Children.count()
React.Children.count()用來(lái)計(jì)數(shù),返回child個(gè)數(shù)。不要用children.length來(lái)計(jì)數(shù),如果Father組件里只有"hello world!"會(huì)返回12,顯然是錯(cuò)誤的結(jié)果。
function Father({children}) { return( <div> {React.Children.count(children)} </div> ) }<Father> hello world! {() => <p>2333</p>}</Father>React.Children.only()
驗(yàn)證children里只有唯一的孩子并返回他。否則這個(gè)方法拋出一個(gè)錯(cuò)誤。
function Father({children}) { return( <div> {React.Children.only(children)} </div> ) }<Father> hello world!</Father>React.Children.toArray()
將children轉(zhuǎn)換成Array,對(duì)children排序時(shí)需要使用
function Father({children}) { let children1 = React.Children.toArray(children); return( <div> {children1.sort().join(" ")} </div> ) }<Father> {"ccc"} {"aaa"} {"bbb"}</Father>//渲染結(jié)果: aaa bbb ccc如果不用React.Children.toArray()方法,直接寫(xiě)children.sort()就會(huì)報(bào)錯(cuò)
Example:
例如有這樣的需求,完成一個(gè)操作需要3個(gè)步驟,每完成一個(gè)步驟,對(duì)應(yīng)的指示燈就會(huì)點(diǎn)亮。
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}> //完成相應(yīng)的步驟,改變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.less
.indicator { display: inline-block; width: 100px; height: 20px; margin-right: 10px; margin-top: 200px; background: #f3f3f3; &.active { background: orange; }推薦學(xué)習(xí):《react視頻教程》
以上就是react children方法怎么用的詳細(xì)內(nèi)容,更多請(qǐng)關(guān)注php中文網(wǎng)其它相關(guān)文章!