2017-09-27 197 views
0

我对react-native语法很困惑。我试图动态渲染包装(CardSection),如果numberChildrenLabel大于0.然后根据数量孩子我想呈现x数量的组件。我目前所做的并不起作用,我认为这是一个相当混乱的问题(即使我修复了语法错误)。基于输入呈现多个组件的最佳方式是什么?动态渲染组件 - React Native

render(){ 
    return(
      ... 
      { 
      this.state.numberChildrenLabel > 0 ? 
      <CardSection> 
      <Text style={{ flex: 2}}>Children age:</Text> 
      <View style={{ flex: 3}}> 
       { 
       for(var i=0; i<this.state.numberChildrenLabel; i++){ 
        return(
        <Text>child{i}</Text> 
       ); 
       } 
       } 
      </View> 
      </CardSection> 
      : 
      <View/> 
      } 
      ... 
    ); 
} 

回答

1

括号里面,你需要一个表达。循环内部是声明。另外,return输出一个函数内的东西;你不能以这种方式使用它。

我还没有测试下面的代码,但它应该工作。

render(){ 
     return(
       ... 
       { 
       this.state.numberChildrenLabel > 0 ? 
       <CardSection> 
       <Text style={{ flex: 2}}>Children age:</Text> 
       <View style={{ flex: 3}}> 
        { 
        Array(this.state.numberChildrenLabel).fill().map((_, i) => i).map(i => <Text>child{i}</Text>) 
        } 
       </View> 
       </CardSection> 
       : 
       <View/> 
       } 
       ... 
     ); 
    }