搜尋
首頁web前端前端問答react children方法怎麼用

react children方法怎麼用

Jan 03, 2023 am 09:45 AM
reactchildren

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()。

react children方法怎麼用

本教學操作環境: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(&#39; &#39;)}
      </div>    
    )        
 }
<Father>
    {&#39;ccc&#39;}
    {&#39;aaa&#39;}
    {&#39;bbb&#39;}
</Father>
//渲染结果: aaa bbb ccc

如果不用React.Children.toArray()方法,直接寫children.sort()就會報錯誤

react children方法怎麼用

Example:

例如有這樣的需求,完成一個操作需要3個步驟,每完成一個步驟,對應的指示燈就會點亮。

index.jsx

import * as React from &#39;react&#39;;
import * as ReactDOM from &#39;react-dom&#39;;
import {Steps, Step} from &#39;./Steps&#39;;
function App() {
    return (
        <div>
        <Steps currentStep={1}>  //完成相应的步骤,改变currentStep的值。如,完成第一步currentStep赋值为1,完成第二部赋值为2
            <Step />
            <Step />
            <Step />
            </Steps>
        </div>
    );
}
ReactDOM.render(<App />, document.getElementById(&#39;root&#39;));

Steps.jsx

import * as React from &#39;react&#39;;
import &#39;./step.less&#39;;
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 ? &#39; active&#39; : &#39;&#39;}`} />;
}
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中文網其他相關文章!

陳述
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
了解usestate():綜合反應國家管理指南了解usestate():綜合反應國家管理指南Apr 25, 2025 am 12:21 AM

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

使用React的優點是什麼?使用React的優點是什麼?Apr 25, 2025 am 12:16 AM

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

在React中調試:識別和解決共同問題在React中調試:識別和解決共同問題Apr 25, 2025 am 12:09 AM

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

反應中的usestate()是什麼?反應中的usestate()是什麼?Apr 25, 2025 am 12:08 AM

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

usestate()與用戶ducer():為您的狀態需求選擇正確的掛鉤usestate()與用戶ducer():為您的狀態需求選擇正確的掛鉤Apr 24, 2025 pm 05:13 PM

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

使用usestate()管理狀態:實用教程使用usestate()管理狀態:實用教程Apr 24, 2025 pm 05:05 PM

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

何時使用usestate()以及何時考慮替代狀態管理解決方案何時使用usestate()以及何時考慮替代狀態管理解決方案Apr 24, 2025 pm 04:49 PM

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

React的可重複使用的組件:增強代碼可維護性和效率React的可重複使用的組件:增強代碼可維護性和效率Apr 24, 2025 pm 04:45 PM

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

See all articles

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

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

AI Clothes Remover

AI Clothes Remover

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

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

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

熱工具

Dreamweaver Mac版

Dreamweaver Mac版

視覺化網頁開發工具

VSCode Windows 64位元 下載

VSCode Windows 64位元 下載

微軟推出的免費、功能強大的一款IDE編輯器

SublimeText3 Mac版

SublimeText3 Mac版

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

Safe Exam Browser

Safe Exam Browser

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

Dreamweaver CS6

Dreamweaver CS6

視覺化網頁開發工具