【问题标题】:How to conditionally use React Native elements如何有条件地使用 React Native 元素
【发布时间】:2019-01-18 10:32:53
【问题描述】:

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

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

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

【问题讨论】:

    标签: reactjs react-native native-base


    【解决方案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>
      }
    }
    

    【讨论】:

    • 谢谢。需要去的整个内容太大并且依赖于屏幕,有没有办法让我可以互换使用 Content 和 View 的功能?例如: const contentorView = () => useContent ? : 然后改用它。但我不确定这种方式是否可行。
    • 你可以做同样的事情,但标签的孩子可以是一个单一的组件。我会更新我的答案。
    【解决方案2】:
    <View>
         booleanCondition1() && <Text> </Text>
         booleanCondition2() && <View> </View>
         booleanConditionN() && { and other elements here }
    </View>
    

    【讨论】:

      【解决方案3】:
      <View>
        {condition == true ?
          (
            <Text> </Text>
            <View> </View>
          )
          :
          (
            { and other elements here }
          )
        }
      </View>
      

      【讨论】:

        猜你喜欢
        • 2021-10-25
        • 1970-01-01
        • 2019-08-31
        • 2022-12-19
        • 1970-01-01
        • 1970-01-01
        • 2020-03-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多