【问题标题】:How do I specify optional prop types in flow?如何在流中指定可选的道具类型?
【发布时间】:2017-10-27 16:47:11
【问题描述】:

我想在外部库定义中声明一个组件(我正在为react-bootstrap 编写流类型),这样我就有了可选和必需的道具,并且没有额外的道具。我有以下内容:

declare export type AlertProps = {|
  bsClass: bsClass,
  bsStyle: ?bsStyle,
  onDismiss: ?(e: SyntheticEvent) => any,
  closeLabel: ?string,
  style: ?style,
|}

declare export class Alert extends React$Component {
  props: AlertProps;
}

(为了这个例子,假设 bsStyle 是实际需要的。)但是,如果我省略 bsClass,流仍然会抱怨

49:     props: AlertProps;
               ^^^^^^^^^^ property `bsClass`. Property not found in
26:       ? (<Alert bsStyle="danger" style={{ textAlign: 'center' }}>
             ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ props of React element `Alert`. See: src/components/audit/AuditAlert.jsx:26

如果我将道具包装在 $Shape&lt;&gt; 中,我就无法获得所需的道具。我的解决方法如下:

declare export type AlertProps = {
  // required props go here
  bsClass: bsClass,
} & $Shape<{|
  // all props (optional and required) go here
  bsClass: bsClass,
  bsStyle: bsStyle,
  onDismiss: (e: SyntheticEvent) => any,
  closeLabel: string,
  style: style,
|}>

但是,这似乎过于 hacky!有没有更好的方法来实现我的目标?

附带说明,this question 未正确回答。

【问题讨论】:

    标签: reactjs flowtype react-proptypes


    【解决方案1】:

    您可以通过放置一个 ? 来指定可选的道具。在属性名称之后。例如

    type Props = {
      optionalString?: string,
      maybeString: ?string,
    }
    

    我可以省略 optionalString,但如果我传递它,它必须是字符串或未定义。 MaybeString 我必须通过,但它的值可以是 null、undefined 或字符串。

    您可以在示例中使用它here

    文档讨论了可选对象属性here

    【讨论】:

    • 嘿,TLadd,为什么 optionalString: undefined 是一个有效值,根据您的评论,如果它存在,它只能是字符串类型?
    • 是的,好点。 undefined 是一个特例,因为{ optionalString: undefined }.optionalString === undefined{}.optionalString === undefined。我猜是? on 属性确实表示访问该属性将返回类型或未定义,无论键是否存在。更新了答案以反映这一点。
    • 我收到eslint 错误:Unexpected token, expect "," 在尝试声明这样的可选 PropType 时:MyComponent.propTypes = { someProp?: PropTypes.bool, ... } 任何想法??
    猜你喜欢
    • 1970-01-01
    • 2018-07-07
    • 2017-04-14
    • 1970-01-01
    • 2022-06-15
    • 2022-11-23
    • 2015-02-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多