[英]Typing in proper way objects as props
目前,我有以下组件
SearchButton.tsx
export interface Props {
// some other props
onClick?: (event: React.MouseEvent<HTMLButtonElement>) => void;
}
export const SearchButton: React.SFC<Props> = ({
// other props
onClick,
})
Popover.tsx
interface ButtonComponentProps {
onClick: (event: React.MouseEvent<HTMLButtonElement>) => void;
}
interface Props {
buttonComponent: React.ComponentType<ButtonComponentProps>;
}
class FilterPopover extends React.Component<Props, State> {
render() {
const {buttonComponent: BtnComponent} = this.props;
return (
<div>
//...
<BtnComponent onClick={this.open} />
</div>
)
}
}
Page.tsx
<Popover buttonComponent={SearchButton}/>
但是我在类型之间有一个不匹配的地方:
The expected type comes from property 'buttonComponent' which is declared here on type 'IntrinsicAttributes & IntrinsicClassAttributes<Popover> & Readonly<{ children?: ReactNode; }> & Readonly<Props>'
因此,如果我从Popover.tsx
更改道具
interface ButtonComponentProps {
onClick?: (event: React.MouseEvent<HTMLButtonElement>) => void;
}
然后接口匹配,但是Typescript如何通过SearchButton
推断此类型? 以这种方式匹配接口可以吗? 为什么这些应该相同?
React 16.4.1打字稿3.0.1
TypeScript正在将SearchButton
的类型(即React.SFC</*SearchButton*/ Props>
与FilterPopover
的buttonComponent
React.SFC</*SearchButton*/ Props>
的类型(即React.ComponentType<ButtonComponentProps>
。 查看React.ComponentType<P>
的定义 ,一个替代方法是React.StatelessComponent<P>
,这是React.SFC<P>
另一个名称。 React.SFC<P>
在P
是不变的,这意味着替换P
的类型( SearchButton
Props
和ButtonComponentProps
)必须完全匹配。
您可能会认为,接受可选道具onClick
的组件应该可以代替接受必需道具的组件可用,因为这仅意味着将始终设置optional属性。 但是,由于声明了无状态组件的可选propTypes
和defaultProps
字段的方式不同,情况并非如此。 我对类型声明设计背后的详细原理不熟悉。 最简单的方法就是完全匹配您的props接口。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.