【问题标题】:Dynamically rendering components - React Native动态渲染组件 - React Native
【发布时间】:2017-09-27 04:32:50
【问题描述】:

我对 react-native 语法很困惑。如果 numberChildrenLabel > 0,我试图动态呈现包装器(CardSection)。然后根据我想要呈现 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/>
          }
          ...
    );
}

【问题讨论】:

    标签: react-native


    【解决方案1】:

    在括号内,您需要一个表达式。 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/>
                  }
                  ...
            );
        }
    

    【讨论】:

      猜你喜欢
      • 2014-12-18
      • 1970-01-01
      • 2020-02-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-25
      • 1970-01-01
      • 2015-02-10
      相关资源
      最近更新 更多