动态渲染组件 - React Native [英] Dynamically rendering components - React Native

查看:104
本文介绍了动态渲染组件 - React Native的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm pretty confused with the react-native syntax. I was trying to dynamically render a wrapper (CardSection) if numberChildrenLabel is > 0. Then depending on the number children I want to render x number of components. What I'm doing currently doesn't work and I think it's a pretty messy (even if I do fix the syntax errors). What is the best way of rendering multiple components based on an input?

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/>
          }
          ...
    );
}

推荐答案

在方括号内,您需要一个表达式.for 循环内部是一个语句.此外,return 从函数内部输出一些东西;你不能以这种方式使用它.

Inside brackets, you need an expression. What's inside for loop is a statement. Also, return outputs something from within a function; you cannot use it in this way.

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

I haven't tested the below code, but it should work.

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/>
              }
              ...
        );
    }

这篇关于动态渲染组件 - React Native的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆