react children方法用於處理“this.props.children”,其處理方式有:1、React.Children.map();2、React.Children.forEach();3、React.Children .count();4、React.Children.only();5、React.Children.toArray()。
本教學操作環境:Windows10系統、react18.0.0版、Dell G3電腦。
react children方法怎麼用?
React.Children詳解
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.Children.map()
#React.Children.map()有些類似Array.prototype.map()。如果children是數組則此方法傳回一個數組,如果是null或undefined則傳回null或undefined。第一參數是children,也就是範例中的Father元件裡的'hello world!'和() =>
2333
函數。第二個參數是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:
例如有這樣的需求,完成一個操作需要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中文網其他相關文章!

useState()isaReacthookusedtomanagestateinfunctionalcomponents.1)Itinitializesandupdatesstate,2)shouldbecalledatthetoplevelofcomponents,3)canleadto'stalestate'ifnotusedcorrectly,and4)performancecanbeoptimizedusinguseCallbackandproperstateupdates.

ReactispupularduetoItsOmpontement,基於虛擬,虛擬詞,Richecosystem和declarativedation.1)基於組件的harchitectureallowslowsforreusableuipieces。

todebugreactapplicationsefectefectionfection,usethestertate:1)proppropdrillingwithcontextapiorredux.2)使用babortControllerToptopRollerTopRollerTopRollerTopRollerTopRollerTopRollerTopRollerTopRollerTopRollerTopRaceeDitions.3)intleleassynChronOusOperations.3)

usestate()inrectallowsStateMagementionInfunctionalComponents.1)ITSIMPLIFIESSTATEMAGEMENT,MACHECODEMORECONCONCISE.2)usetheprevcountfunctionToupdateStateBasedonitspReviousViousViousvalue,deveingingStaleStateissues.3)

selectUsestate()forsimple,獨立的variables; useusereducer()forcomplexstateLogicorWhenStatedIppedsonPreviousState.1)usestate()isidealForsImpleupDatesLikeToggGlikGlingaBglingAboolAboolAupDatingacount.2

useState優於類組件和其它狀態管理方案,因為它簡化了狀態管理,使代碼更清晰、更易讀,並與React的聲明性本質一致。 1)useState允許在函數組件中直接聲明狀態變量,2)它通過鉤子機制在重新渲染間記住狀態,3)使用useState可以利用React的優化如備忘錄化,提升性能,4)但需注意只能在組件頂層或自定義鉤子中調用,避免在循環、條件或嵌套函數中使用。

useUsestate()forlocalComponentStateMangementighatighation; 1)usestate()isidealforsimple,localforsimple.2)useglobalstate.2)useglobalstateSolutionsLikErcontExtforsharedState.3)

ReusableComponentsInrectenHanceCodainainability and效率byallowingDevelostEsteSeTheseTheseThesAmeCompOntionActActRossDifferentPartSofanApplicationorprojects.1)heSredunceRedUndenceNandSimplifyUpdates.2)yensureconsistencyInuserexperience.3)


熱AI工具

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

Video Face Swap
使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

熱工具

Dreamweaver Mac版
視覺化網頁開發工具

VSCode Windows 64位元 下載
微軟推出的免費、功能強大的一款IDE編輯器

SublimeText3 Mac版
神級程式碼編輯軟體(SublimeText3)

Safe Exam Browser
Safe Exam Browser是一個安全的瀏覽器環境,安全地進行線上考試。該軟體將任何電腦變成一個安全的工作站。它控制對任何實用工具的訪問,並防止學生使用未經授權的資源。

Dreamweaver CS6
視覺化網頁開發工具