【发布时间】:2019-07-29 18:13:23
【问题描述】:
我正在创建一个如下所示的组件:
<Button component='a' href='/'>
Link
</Button>
我想获取component 属性的类型定义,所以我可以自动将它包含在Button 组件的属性中。关于Button 组件的接口/类型应该是什么样子的任何想法
【问题讨论】:
标签: javascript reactjs typescript
我正在创建一个如下所示的组件:
<Button component='a' href='/'>
Link
</Button>
我想获取component 属性的类型定义,所以我可以自动将它包含在Button 组件的属性中。关于Button 组件的接口/类型应该是什么样子的任何想法
【问题讨论】:
标签: javascript reactjs typescript
我以前使用过这种模式。声明 React.ComponentType<T> | string 类型的 component 属性。你的Button 组件应该看起来像这样:
export interface ButtonProps {
component?: React.ComponentType<any>; // or React.ReactElement<any>["type"]
href?: string;
children?: React.ReactNode;
}
export function Button(props: ButtonProps) {
const {
component: Component = "button", // note: uppercase
children,
...other
} = props;
return (
<Component {...other}>
{children}
</Component>
);
}
【讨论】:
...other 道具?
any 会覆盖它,但这有点小技巧。也许使用React.ComponentType<React.AnchorHTMLAttributes<HTMLAnchorElement> | React.ButtonHTMLAttributes<HTMLButtonElement>>,或者声明你想要支持的组件上的哪些道具。
您的Button 组件可以这样输入:
import * as React from 'react';
type ButtonProps = {
component: string,
href: string,
}
type ButtonState = {}
export default class Button extends React.Component<ButtonProps , ButtonState > {
constructor(props) {
super(props);
this.state = {}
}
render() { return <div/> }
}
我写了一篇关于从头到尾构建TypeScript + React 应用程序的整篇文章,请查看完整的详细信息和解释!
【讨论】: