【问题标题】:react native conditional rendering反应原生条件渲染
【发布时间】:2017-06-24 14:31:47
【问题描述】:

我正在尝试使用内联 if 语句来检查一条数据是否存在以及是否显示它。此代码当前位于我的渲染、返回块中。

我遇到的问题是使用它,内容不再被呈现

{(() => {
              if (this.props.data.size) {
                <Text style={styles.headerLabel}>Sizes</Text>
                {(this.props.data.size||[]).map((section,i) => (
                  <AddToCartRow key={i} data={section} productName={this.props.data.name} value={Config.priceToPriceWithCurrency(section.price)} />
                ))}
              }
            })()}

【问题讨论】:

标签: if-statement react-native conditional render


【解决方案1】:

render(){
  return(
    <View>
    {this.state.error && <Text style={{ color: 'red' }}>{this.state.errorMessage}</Text>}
    <Text>Hello World!</Text>
    </View>
  );
}

你去。

【讨论】:

  • 抱歉。我刚刚点击了上面的“运行代码sn-p”按钮,结果显示报错。但我认为这与您的代码无关。对不起。
【解决方案2】:

下面的代码也检查空字符串。

render(){
  return(
    <View>
    {!!this.state.error && <Text>{this.state.errorMessage}</Text>}
    </View>
  );
}

【讨论】:

  • 这其实是更准确的答案
【解决方案3】:

尝试使用这个 eslint 规则:

"no-restricted-syntax": [
  "error",

  ...otherRules,

  // Two rules below help us avoid this common point of confusion: https://stackoverflow.com/q/53048037
  // The selectors are inspired by https://github.com/yannickcr/eslint-plugin-react/issues/2073#issuecomment-844344470
  {
    selector:
      ":matches(JSXElement, JSXFragment) > JSXExpressionContainer > LogicalExpression[operator='&&']",
    message:
      "Please use `condition ? <Jsx /> : null`. Otherwise, there is a chance of rendering '0' instead of '' in some cases. Context: https://stackoverflow.com/q/53048037",
  },
  {
    selector:
      ":matches(JSXElement, JSXFragment) > JSXExpressionContainer > LogicalExpression[operator='||']",
    message:
      "Please use `value ?? fallbackValue`. Otherwise, there is a chance of rendering '0' instead of '' in some cases. Context: https://stackoverflow.com/q/53048037",
  },
],

链接:https://github.com/yannickcr/eslint-plugin-react/issues/2073#issuecomment-864168062

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-17
    • 2019-03-25
    • 2021-05-01
    相关资源
    最近更新 更多