2017-01-26 78 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> 
); 
};