1. 程式人生 > 實用技巧 >React props.children

React props.children

它表示元件所有的子節點。在元件內部使用this.props.children,可以拿到使用者在元件裡面放置的內容。

資料型別PropTypes

  • 如果當前沒有子節點,它就是undefined
  • 如果只有一個子節點,資料型別是object
  • 如果有多個子節點,資料型別是Array

可以使用PropTypes進行型別檢測

使用PropTypes.element,可以指定僅將單一子元素傳遞給元件,作為子節點。

MyComponent.propTypes = {
  children: PropTypes.element.isRequired
};

不確定 props.children 會被傳入一個還是多個子節點時,可以使用PropTypes.node

型別,代表任何可被渲染的元素(包括數字、字串、元素或陣列)。

MyComponent.propTypes = {
  children: PropTypes.node
};

React.Children

React 提供了工具方法 React.Children 來處理 this.props.children。

1. React.Children.map

object React.Children.map(object children, function fn)
遍歷 props.children ,在每一個子節點上呼叫 fn 函式。

2. React.Children.forEach

React.Children.forEach(object children, function fn)

類似於 React.Children.map(),但是不返回物件。

3. React.Children.count

number React.Children.count(object children)
返回 children 當中的元件總數。

4. React.Children.only

object React.Children.only(object children)
返回 children 中僅有的子節點。如果在 props.children 傳入多個子節點,將會丟擲異常。

原文連結:https://blog.csdn.net/u012372720/java/article/details/94000150