动态渲染组件 - React Native

时间:2017-09-27 04:32:51

标签: react-native

我对react-native语法很困惑。如果numberChildrenLabel是>我试图动态渲染包装器(CardSection)。 0.然后根据孩子的数量,我想渲染x个组件。我目前正在做什么不起作用,我认为这是一个非常混乱(即使我确实修复了语法错误)。基于输入渲染多个组件的最佳方法是什么?

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 个答案:

答案 0 :(得分:2)

在括号内,您需要一个表达式。 for循环中的内容是语句。此外,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/>
              }
              ...
        );
    }