【问题标题】:Require React-Native conditionally有条件地需要 React-Native
【发布时间】:2019-07-24 21:53:46
【问题描述】:

我想创建一个通用元素,它在 Web 中返回 div,在 React-Native 中返回 View。 目前,它看起来像这样:

export const Element = ({children, ...rest}) => {
  if (typeof document != 'undefined') {
    return <div {...rest}>{children}</div>
  } 
  try {
    const View  = require('react-native').View;
    return <View {...rest}>{children}</View>
  } catch (e) {
    return {};
  }
};

我使用 try-catch 是因为我收到此错误:

找不到模块:错误:无法解析“react-native”

如何在不需要 try-catch 的情况下有条件地需要 React-Native?

【问题讨论】:

    标签: reactjs react-native


    【解决方案1】:

    您可以尝试导入 react-native 外部函数,例如

    import { View } from 'react-native'
    
    export const Element = ({children, ...rest}) => {
      if (typeof document != 'undefined') {
        return <div {...rest}>{children}</div>
      } 
        return <View {...rest}>{children}</View>
    };
    

    可能对你有帮助。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-12-20
      • 1970-01-01
      • 2018-11-29
      • 2016-06-22
      • 2016-12-07
      • 1970-01-01
      • 2020-02-18
      相关资源
      最近更新 更多