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

时间:2019-01-18 10:32:53

标签: reactjs react-native native-base

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

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

但是在另一种情况下,我需要View必须是nativeBase中的Content。 如果useContent变量为true,则使用Content作为包装器呈现所有内容,否则使用View。 我最好怎么做?

3 个答案:

答案 0 :(得分:1)

使用三元运算符可以帮助您有条件地进行渲染。

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>
  }
}

答案 1 :(得分:0)

<View>
     booleanCondition1() && <Text> </Text>
     booleanCondition2() && <View> </View>
     booleanConditionN() && { and other elements here }
</View>

答案 2 :(得分:0)

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