זהו נושא דיון מלווה לערך המקורי שב־https://www.tocode.co.il/bundles/react/lessons/react-children
מדוע צריך את הפונקציה count בשביל לקבל את מספר הילדים,
React.Children.count(props.children);
ולא להשתמש פשוט ב-length?
props.children.length
הי,
יש הסבר מצוין על ההבדלים כאן:
נסה לקרוא וספר אם הבנת
1.) בקישור הנ"ל מסבירים את ההבדלים בין:
React.Children.count(props.children)
ל - React.Children.toArray(props.children).length
ואני מתכוונת להבדלים בין -
React.Children.count(props.children)
ל - props.children.length
ניסיתי להוסיף הדפסות לקוד הזה:
<MyFormsContainer>
<Login/>
<CountryAndCity/>
{false && <Hobbies/>}
<Summary/>
</MyFormsContainer>
ומההדפסות נראה שזה יוצא אותו דבר:
console.log(React.Children.count(props.children)); //prints 4
console.log(props.children.length); //prints 4
לעומת זאת:
console.log(React.Children.toArray(props.children).length); //prints 3
2.) ודבר נוסף:
(React.Children.toArray(props.children
- מחזיר מערך בלי האיבר ששווה ל-false ז"א שבמקרה הזה המערך הוא בגודל 3, יוצא שעדיף בכלל להשתמש ב - React.Children.toArray(props.children).length
שמחזיר את הגודל האמיתי - אחרת תהיה חריגה מגבולות המערך.
יפה אנחנו מתקרבים
עכשיו נסי לבדוק מה את מקבלת כשאין ילדים ל MyFormsContainer
הבנתי,
במקרה שאין ילדים אז ה-count יחזיר 0 וה-props.children.length לא יקבל ערך כיון ש-children הוא undefined.
תודה!