【问题标题】:Rendering a component with ternary expression使用三元表达式渲染组件
【发布时间】:2019-02-21 20:22:09
【问题描述】:

我去使用三元表达式渲染一个组件。

目前我正在做这样的事情

 <View style={container}>
          { this.state.loaded ? 
                            (<VictoryChart
                    theme={VictoryTheme.material}
                    >
                    <VictoryArea
                        style={{ data: { fill: "#c43a31" } }}
                        data={this.coinHistoryData} 
                        x="cHT"
                        y="cHTVU"
                        domain={{ y: [0, 30000] }}
                    />
                    </VictoryChart>)
          : (<Text> Loading..</Text>)}  </View>

但这不起作用并抛出错误说Invariant Violation

ExceptionsManager.js:84 未处理的 JS 异常:不变违规: 不变违规:文本字符串必须在 组件。

[问题:]如何修复它并在三元表达式中渲染整个组件

Ps:据此stackoverflow question:当我们进行内联条件渲染时会发生这种情况。

【问题讨论】:

  • 你是说 this.state.loaded 吗?
  • this.setState.loaded?你的意思是this.state.loaded
  • 修复了!我的意思是this.state.loaded@Zunino
  • this.state.loaded@davidhu2000
  • 这是 react-native 吗?你导入Text了吗?

标签: javascript reactjs react-native


【解决方案1】:

我以前在 react-native 看到过。
我知道有两个原因会引发此错误:

  1. 返回null / undefined(我认为不是你的情况)
  2. &lt;/Text&gt; 标签后的空格(我认为这是你的情况)

所以去掉最后的空格:

<View style={container}>
          { this.state.loaded ? 
                            (<VictoryChart
                    theme={VictoryTheme.material}
                    >
                    <VictoryArea
                        style={{ data: { fill: "#c43a31" } }}
                        data={this.coinHistoryData} 
                        x="cHT"
                        y="cHTVU"
                        domain={{ y: [0, 30000] }}
                    />
                    </VictoryChart>)
          : (<Text> Loading..</Text>)}  </View> //<--- spaces are here

所以这一行

: (<Text> Loading..</Text>)}  </View> 

应该是这样的

: (<Text> Loading..</Text>)}</View> 

【讨论】:

  • ...这就是为什么模式 {condition &amp;&amp; (&lt;component&gt;)}{!condition &amp;&amp; (&lt;anotherComponent&gt;)} 对于 React Native 看起来更安全。没有意外添加额外的文字:)
猜你喜欢
  • 2020-12-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-04
  • 2021-06-16
  • 2021-12-08
  • 2012-12-06
  • 2019-05-05
相关资源
最近更新 更多