Rob*_*cki 5 reactjs flowtype react-proptypes
我想在外部库定义中声明一个组件(我正在编写流类型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;
}
Run Code Online (Sandbox Code Playgroud)
(为了这个例子,我们假设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
Run Code Online (Sandbox Code Playgroud)
如果我将道具包裹起来$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,
|}>
Run Code Online (Sandbox Code Playgroud)
但是,这似乎过于苛刻!有没有更好的方法来实现我的目标?
作为旁注,这个问题没有得到正确回答.
TLa*_*add 13
你可以通过放置一个指定可选的道具?在属性名称之后.例如
type Props = {
optionalString?: string,
maybeString: ?string,
}
Run Code Online (Sandbox Code Playgroud)
我可以省略optionalString,但如果我传递它,它必须是一个字符串.maybeString我必须传递,但它的值可以是null,undefined或字符串.
你可以在这里举例说明
该文档谈可选对象属性在这里.
| 归档时间: |
|
| 查看次数: |
4370 次 |
| 最近记录: |