반응 자식 메서드는 "this.props.children"을 처리하는 데 사용됩니다. 1. React.Children.map() 2. React.Children.forEach(); () ; 4. React.Children.only(); 5. React.Children.toArray().
이 튜토리얼의 운영 환경: Windows 10 시스템, 반응 버전 18.0.0, Dell G3 컴퓨터.
반응 어린이 방법을 사용하는 방법은 무엇입니까?
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()과 다소 유사합니다. 이 메서드는 자식이 배열인 경우 배열을 반환하고, null이거나 정의되지 않은 경우 null 또는 정의되지 않은 것을 반환합니다. 첫 번째 매개변수는 children이며, 이 예에서는 Father 구성요소의 'hello world!' 및 () =>2333
두 번째 매개변수는 function 이고, 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()는 자녀 수를 계산하고 반환하는 데 사용됩니다. 계산에 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()
자식을 배열로 변환합니다. 자식을 정렬할 때
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()가 직접 보고됩니다.
예:
예를 들어 이러한 요구 사항이 있는 경우 작업을 완료하려면 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 비디오 튜토리얼"
위 내용은 반응 어린이 방법을 사용하는 방법의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

usestate () isareacthookusedtomanagestatefunctionalcomponents.1) itinitializesandupdatesstate, 2) workaledtthetThetThepleFcomponents, 3) canleadto'Stalestate'ifnotusedCorrecrally 및 4) performancanoptimizedUsecandusecaldates.

Reactispopularduetoitscomponent 기반 아카데입, 가상, Richcosystem 및 declarativenature.1) 구성 요소 기반 ectureallowsforeusableuipieces, Modularityandmainability 개선 가능성.

TodebugreactApplicationseffective, UsetheseStradegies : 1) 주소 propdrillingwithContapiorredux.2) handleaSnchronousOperationswithUsestAndUseefect, abortControllerTopReceConditions.3) 최적화 formanceSeMoAnduseCalbackTooid

usestate () inreactAllowsStateManagementInfunctionalComponents.1) itsimplifiessTatemanagement, 2) usethepRevCountFunctionToupDatesTestateSpreviousValue, PropeingStaleScallanceBackferperperperperperperperperperperperperpertoptiMizatio

chelectionSimple, IndependentStateVaribles; useUserEducer () useuserEducer () forcomplexStateLogicor () whenStatedSonpreviousState.1) usestate () isidealforsimpleupdatesliketogglingabooleorupdatingacounter.2) usbetterformanagingmentiplesub-vvalusorac

Usestate는 클래스 구성 요소 및 기타 상태 관리 솔루션보다 우수합니다. 국가 관리를 단순화하고 코드를 더 명확하게하고 읽기 쉽고 React의 선언적 특성과 일치하기 때문입니다. 1) Usestate는 함수 구성 요소에서 상태 변수를 직접 선포 할 수있게합니다. 2) 후크 메커니즘을 통해 다시 렌더링하는 동안 상태를 기억합니다.

useUsestate () forlocalcomponentStateManagement; 고려 사항 forglobalstate, complexlogic, orperformanceissues.1) usestate () isidealforsimple, localstate.2) useglobalstatesolutionslikereduxorcontextforsharedstate.3) optforredooxtoolkitormobxcomcoccomcoccomcoccomcoccomcoccomcoccomcoccomcoccomporccomcoccomporccomcoccomport

reusablecomponentsinreacececodemainabenabilityandefficiency는 hallowingesamecomponentacrossdifferentpartsofanapplicationorprojects.1) 그들을 retuduceredundancyandsimplifyupdates.2) theyseconsistencyinuserexperience.3) theyquireoptim


핫 AI 도구

Undresser.AI Undress
사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover
사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool
무료로 이미지를 벗다

Clothoff.io
AI 옷 제거제

Video Face Swap
완전히 무료인 AI 얼굴 교환 도구를 사용하여 모든 비디오의 얼굴을 쉽게 바꾸세요!

인기 기사

뜨거운 도구

에디트플러스 중국어 크랙 버전
작은 크기, 구문 강조, 코드 프롬프트 기능을 지원하지 않음

Dreamweaver Mac版
시각적 웹 개발 도구

메모장++7.3.1
사용하기 쉬운 무료 코드 편집기

맨티스BT
Mantis는 제품 결함 추적을 돕기 위해 설계된 배포하기 쉬운 웹 기반 결함 추적 도구입니다. PHP, MySQL 및 웹 서버가 필요합니다. 데모 및 호스팅 서비스를 확인해 보세요.

드림위버 CS6
시각적 웹 개발 도구
