加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

reactjs – 如何在流中指定可选的prop类型?

发布时间:2020-12-15 05:06:01 所属栏目:百科 来源:网络整理
导读:我想在外部库定义中声明一个组件(我正在为react-bootstrap编写流类型),这样我就有了可选和必需的道具,而且没有额外的道具.我有以下内容: declare export type AlertProps = {| bsClass: bsClass,bsStyle: ?bsStyle,onDismiss: ?(e: SyntheticEvent) = any,c
我想在外部库定义中声明一个组件(我正在为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<>中,我就不能拥有所需的道具.我的解决方法如下:

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

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

作为旁注,this question未得到正确回答.

你可以通过放置一个指定可选的道具?在属性名称之后.例如
type Props = {
  optionalString?: string,maybeString: ?string,}

我可以省略optionalString,但如果我传递它,它必须是一个字符串. maybeString我必须传递,但它的值可以是null,undefined或字符串.

您可以在示例here中使用它

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读