如何有条件地使用 React Native 元素

How to conditionally use React Native elements

我需要根据特定条件使用不同的包装器来渲染屏幕。 例如,我有一种情况需要将内容包装在视图中

      <View>
         <Text> </Text>
         <View> </View>
         { and other elements here }
      </View>

但是在不同的场景下,我需要View是来自nativeBase的Content。 如果 useContent 变量为真,则使用 Content 作为包装器呈现所有内容,否则使用 View。 我最好怎么做?

<View>
     booleanCondition1() && <Text> </Text>
     booleanCondition2() && <View> </View>
     booleanConditionN() && { and other elements here }
</View>
<View>
  {condition == true ?
    (
      <Text> </Text>
      <View> </View>
    )
    :
    (
      { and other elements here }
    )
  }
</View>

使用三元运算符来帮助您有条件地渲染。

render() {
  const useContent = true;

  return useContent ? (
    <Content>
      <Text></Text>
      <View></View>
    </Content>
  ) : (
    <View>
      <Text></Text>
      <View></View>
    </View>
  )
}

也可能把这两块抽离成自己的组件比较好。这样您的组件文件就不会变得太大,并且可维护性开始成为一个问题。 编辑:如果您想让组件的子组件保持不变,只是更改包装元素,请创建第二个呈现子组件的组件:

class WrappingElement extends Component {
  render() {
    const { children, useContent } = this.props;

    return useContent ? (
      <Content>{children}</Content>
    ) : (
      <View>{children}</View>
    )
  }
}

class Foo extends Component {
  render() {
    <WrappingElement useContent={false}>
      <Text>Hello World!</Text>
      <View></View>
    </WrappingElement>
  }
}