本教程操作環(huán)境:Windows10系統(tǒng)、react18.0.0版、Dell G3電腦。
【資料圖】
react children方法怎么用?
React.Children詳解
React.Children提供了處理this.props.children的工具,this.props.children可以任何數(shù)據(組件、字符串、函數(shù)等等)。React.children有5個方法:React.Children.map(),React.Children.forEach()、React.Children.count()、React.Children.only()、React.Children.toArray(),通常與React.cloneElement()結合使用來操作this.props.children。
React.Children.map()
React.Children.map()有些類似Array.prototype.map()。如果children是數(shù)組則此方法返回一個數(shù)組,如果是null或undefined則返回null或undefined。第一參數(shù)是children,即示例中的Father組件里的"hello world!"和() => <p>2333</p>函數(shù)。第二個參數(shù)是fucntion,function的參數(shù)第一個是遍歷的每一項,第二個是對應的索引。
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ū)別在于無返回。
React.Children.count()
React.Children.count()用來計數(shù),返回child個數(shù)。不要用children.length來計數(shù),如果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:
例如有這樣的需求,完成一個操作需要3個步驟,每完成一個步驟,對應的指示燈就會點亮。
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.less
.indicator { display: inline-block; width: 100px; height: 20px; margin-right: 10px; margin-top: 200px; background: #f3f3f3; &.active { background: orange; }推薦學習:《react視頻教程》
以上就是react children方法怎么用的詳細內容,更多請關注php中文網其它相關文章!