【问题标题】:Can't add multiple lines of components into variable无法将多行组件添加到变量中
【发布时间】:2016-11-10 12:54:17
【问题描述】:

我想根据 if 语句的结果将内容保存在变量中。但是当我添加多行时它不起作用。

let content = null
if(this.props.group.name != null){
  content = <Text>Just this line works</Text>
              <Text>This doesn't work</Text>
}

我不知道该怎么做。我不能像在 Javascript 中那样在行尾添加 +。

【问题讨论】:

  • 你不能把它加在一起吗?像这样 - content = &lt;Text&gt;Just this line works&lt;/Text&gt; &lt;Text&gt;This doesn't work&lt;/Text&gt;
  • 内容更多时不会。这只是一个例子。

标签: reactjs react-native jsx


【解决方案1】:

组件需要包装在包含父组件的组件中,除非您将其创建为带有键的数组。

// this would work because it's wrapped inside parentheses and has a parent component
content = (
          <View>
            <Text>Just this line works</Text>
            <Text>This doesn't work</Text>
          </View>
          )

// this works because the components are an array
content = [
           <Text key="1">Just this line works</Text>,
           <Text key="2">This doesn't work</Text>
          ]

【讨论】:

  • 谢谢你的工作!我尝试了括号,但我不知道您还需要包装它。
  • @SinanSamet 很高兴我能帮上忙!
猜你喜欢
  • 2013-04-29
  • 2018-10-12
  • 2017-07-11
  • 1970-01-01
  • 2013-09-05
  • 1970-01-01
  • 2021-02-28
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多