【问题标题】:Setting types in RN with TS使用 TS 在 RN 中设置类型
【发布时间】:2019-07-15 04:21:02
【问题描述】:

在我的 RN 应用程序中,我有以下界面。

interface IProps extends Props<IProps> {
  label?: string;
  editable?: boolean;
  maxLength?: number;
  autoCorrect?: boolean;
  placeholder?: string;
  // tslint:disable-next-line: max-line-length
  autoCapitalize?: 'none' | 'sentences' | 'words' | 'characters' | undefined;
  // tslint:disable-next-line: max-line-length
  returnKeyType?: 'none' | 'done' | 'search' | 'default' | 'go' | 'next' | 'send' | 'previous' | 'google' | 'join' | 'route' | 'yahoo' | 'emergency-call';
  // tslint:disable-next-line: max-line-length
  keyboardType?: 'default' | 'email-address' | 'numeric' | 'phone-pad' | 'visible-password' | 'ascii-capable' | 'numbers-and-punctuation' | 'url' | 'number-pad' | 'name-phone-pad' | 'decimal-pad' | 'twitter' | 'web-search' | undefined;
  secureTextEntry?: boolean;
  inputStyle?: object;
  containerStyle?: object;
  inputContainerStyle?: object;
}

这里的autoCapitalize,returnKeyType的类型是一个枚举。在这里定义整个枚举似乎很难看。有更好的方法吗?

【问题讨论】:

    标签: reactjs typescript react-native


    【解决方案1】:

    试试这个:

    enum AutoCapitalize {
      NONE = 'none',
      SENTENCES = 'sentences',
      WORDS = 'words',
      CHARACTERS = 'characters',
      UNDEFINED = '',
    }
    
    enum ReturnKeyType {
      ...
    }
    
    interface IProps extends Props<IProps> {
      label?: string;
      editable?: boolean;
      maxLength?: number;
      autoCorrect?: boolean;
      placeholder?: string;
      // tslint:disable-next-line: max-line-length
      autoCapitalize?: AutoCapitalize;
      ...
    }
    

    【讨论】:

    • type 将是另一个不错的选择。枚举很好,但你必须在传递值或类型检查抱怨时使用它们
    • 一个type?在嵌套数据模型的情况下而不是在值是基元的情况下,这不是更有意义吗?
    • 这取决于使用情况,&lt;Input autoCorrect={AutoCapitalize.SENTENCES}&lt;Input autoCorrect="sentences" 用于 DOM 属性和与之相关的东西(比如 &lt;Input type="text" 我个人可能只使用类型和字符串属性。只是一个偏好:) +1 无论如何
    猜你喜欢
    • 2023-03-30
    • 1970-01-01
    • 2017-05-31
    • 1970-01-01
    • 2020-08-11
    • 2020-03-22
    • 1970-01-01
    • 1970-01-01
    • 2020-09-13
    相关资源
    最近更新 更多