我一直在搜索许多论坛和文章,但没有找到任何成功的方法来为React中的功能组件定义接口,该接口具有在defaultProps中定义的必需属性,而不会引发“缺少属性” Typescript错误。
我试图直接在props中设置默认值,但是它也不起作用。有什么办法还是React和Typescript中未解决的问题?
为了实际解决此问题,我提供了CodeSandbox项目。
type ButtonProps = {
color: "white" | "green";
};
const Button: FunctionComponent<ButtonProps> = ({
// First way to define default value
color = "green",
children
}) => <ButtonContainer>{children}</ButtonContainer>;
// Second way to define default value
Button.defaultProps = {
color: "white"
} as Partial<ButtonProps>;
const ButtonContainer = styled.button<ButtonProps>`
background-color: ${(props: ButtonProps) => props.color};
`;
const App: FunctionComponent = () => (
<div className="App">
<h1>Hello CodeSandbox</h1>
<h2>Start editing to see some magic happen!</h2>
{/* Here is an error */}
<Button>hello world</Button>
</div>
);
由于color
是ButtonProps
类型的唯一属性,因此可以使用Partial,它将部分类型的属性设置为可选:
const Button: FunctionComponent<Partial<ButtonProps>> = ({
// First way to define default value
color = "green",
children
}) => <ButtonContainer>{children}</ButtonContainer>;
这是一个工作示例。
编辑:
跟进您的评论,这是我的建议。我们可以删除defaultProps
和ButtonProps
来定义的类型ButtonContainer
。在Button
组件上,您可以简单地将剩余的道具散布到孩子身上ButtonContainer
。
type ButtonProps = {
color: "white" | "green";
fontSize: string;
};
const Button: FunctionComponent<Partial<ButtonProps>> = ({
// First way to define default value
children,
...styleProps
}) => <ButtonContainer {...styleProps}>{children}</ButtonContainer>;
const ButtonContainer = styled.button<ButtonProps>`
background-color: ${(props: ButtonProps) => props.color};
font-size: ${(props: ButtonProps) => props.fontSize};
`;
const App: FunctionComponent = () => (
<div className="App">
<h1>Hello CodeSandbox</h1>
<h2>Start editing to see some magic happen!</h2>
<Button color='green'>hello world</Button>
</div>
);
这是更新的演示。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句