Reactjs 以适当的方式键入对象作为道具
目前我有以下组件 SearchButton.tsxReactjs 以适当的方式键入对象作为道具,reactjs,typescript,Reactjs,Typescript,目前我有以下组件 SearchButton.tsx export interface Props { // some other props onClick?: (event: React.MouseEvent<HTMLButtonElement>) => void; } export const SearchButton: React.SFC<Props> = ({ // other props onClick, }) interface Bu
export interface Props {
// some other props
onClick?: (event: React.MouseEvent<HTMLButtonElement>) => void;
}
export const SearchButton: React.SFC<Props> = ({
// other props
onClick,
})
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>
)
}
}
<Popover buttonComponent={SearchButton}/>
然后接口匹配,但是Typescript是如何通过SearchButton
推断这种类型的呢?这样匹配接口可以吗?为什么那些应该是一样的
反应16.4.1类型脚本3.0.1
TypeScript正在将
SearchButton
的类型(即React.SFC
)与FilterPover
的buttonComponent
属性(即React.ComponentType
)进行比较。现在来看,一种替代方法是React.StatelessComponent
,它是React.SFC
的另一个名称React.SFC
在P
中是不变的,这意味着被P
替换的类型(SearchButton
Props和ButtonComponentProps
)必须完全匹配
您可能认为接受可选道具的组件应该可以替代接受所需道具的组件,因为这意味着将始终设置可选属性。然而,事实并非如此,因为已经宣布的方式。我不熟悉类型声明设计背后的详细原理。最简单的方法就是精确匹配你的道具界面
The expected type comes from property 'buttonComponent' which is declared here on type 'IntrinsicAttributes & IntrinsicClassAttributes<Popover> & Readonly<{ children?: ReactNode; }> & Readonly<Props>'
interface ButtonComponentProps {
onClick?: (event: React.MouseEvent<HTMLButtonElement>) => void;
}