2017-01-26 81 views
1

我正在研究反應本機應用程序,並且爲顯示列表項目創建了一個公共組件。在無狀態組件中迭代兒童反應/反應本機

<View style={styles.container}> 
    <ItemsWithSeparator style={styles.itemsContainer}> 
    <AppRow /> 
    <AppRow /> 
    </ItemsWithSeparator> 
</View> 

現在,我的ItemListSeparator只是迭代孩子和呈現列表,所以我想我會讓這個無狀態的組件。

const ItemsWithSeparator = function ({children,style}) { 
    const childrenList = []; 
    const length = React.Children.count(children); 
    React.Children.forEach(
    children, 
    (child,ii) => { 
     childrenList.push(child); 
     if (ii !== length -1) { 
     childrenList.push(
      <View 
      key={`separator-${ii}`} 
      style={[styles.separator]} 
      /> 
     ); 
     } 
    } 
); 
    return (
    <View style={style}> 
     {children} 
    </View> 
); 
}; 

但是,這會引發錯誤,說'找不到'反應'。

但是,它適用於基於類的組件。以下是正常工作的代碼。

class ItemsWithSeparator extends React.Component { 

    render() { 
    const {children,style} = this.props; 
    const childrenList = []; 
    const length = React.Children.count(children); 
    React.Children.forEach(
     children, 
     (child,ii) => { 
     childrenList.push(child); 
     if (ii !== length -1) { 
      childrenList.push(
      <View 
       key={`separator-${ii}`} 
       style={[styles.separator]} 
      /> 
     ); 
     } 
     } 
    ); 
    return (
     <View style={style}> 
     {children} 
     </View> 
    ); 
    } 
} 

任何人都可以幫助我理解這一點嗎? TIA!

更新:

我只是想一些東西,顯然得到了他的工作: -

const ItemsWithSeparator = function ({children,style,...props}) { 
    const childrenList = []; 
    const length = React.Children.count(children); 
    React.Children.forEach(
    children, 
    (child,ii) => { 
     childrenList.push(child); 
     if (ii !== length -1) { 
     childrenList.push(
      <View 
      key={`separator-${ii}`} 
      style={[styles.separator]} 
      {...props} 
      /> 
     ); 
     } 
    } 
); 
    return (
    <View style={style}> 
     {children} 
    </View> 
); 
}; 

但我仍然對如何爲這個工作有點混亂。如果有人能解釋我真的會很棒。

+0

您是否對您的文件導入了反應? –

+0

是的,我沒有進口反應 –

+0

嗯,但你爲什麼使用React.children,如果你有你自己的財產兒童?真的很奇怪的錯誤:) –

回答

3

這裏是重構版本,所以你不必做這個奇怪的React.Children的東西:D注意,你可以返回數組映射的孩子。如果需要,您可以製作if語句。

const ItemsWithSeparator = ({children, style, ...props}) => { 
    const finalFields = children.map((child, index) => { 
    return [ 
     child, 
     index !== children.length - 1 && (
     <View key={index} {...props} style={styles.separator} /> 
    ) 
    ]; 
    }); 

    return (
    <View style={style}> 
     {finalFields} 
    </View> 
); 
};