反应本机条件渲染

react native conditional rendering

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

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

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

给你。

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

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

尝试使用这个 eslint 规则:

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

  ...otherRules,

  // Two rules below help us avoid this common point of confusion: 
  // 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: ",
  },
  {
    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: ",
  },
],

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

一般来说,React Native 中的条件渲染与 React 中的相同。但请注意,在 React Native 中,我们只能在 Text 组件内渲染字符串。因此,例如,如果我们尝试将字符串放入 View 中,它将引发错误。

内联 if 使用逻辑 && 运算符。

<View>
  {!!error && <ErrorMessage />}
</View>

⚠️ 双重否定运算符!!在这里非常重要(我们也可以使用Boolean函数)因为它确保条件的左边部分将是一个布尔值。

为什么重要?因为逻辑“与”运算符 && 将 return 条件的右侧,如果左侧是 truthy,并且将 return 条件的左侧,如果左侧边是 falsy.

成像我们有一个组件:

<View>
  {error && <ErrorMessage />}
</View>

如果 error 变量是 object / null / undefined 一切都会按预期工作。但是,如果我们得到一个空字符串作为错误 (error = ''),那么我们的组件就会停止,因为我们无法在 View 组件中渲染字符串。

// error = ''
// {error && <something>} will return the error variable (which equals to '')
// and we will get:
<View>
  ''
</View>
// which will throw an error (can't render strings inside a View )

使用三元 ? 运算符内联 if-else。

{error ? <ErrorMessage /> : <SuccessMessage />}

{error ? <ErrorMessage /> : null}

这里我们可以return null 或者<></> (React Fragment) 取决于我们的组件结构和return类型

if 声明

...

const Error = () => {
  if (!error) {
    return null
  }

  return <ErrorMessage />
}

return (
  <View>
    <Error />
  </View>
)

代码示例

请使用 this Expo Snack 查看完整代码并使用它。