javascript - 如何使用 defaultProps 为 React 函数组件定义接口而不抛出缺少类型错误?
问题描述
我一直在搜索许多论坛和文章,但没有找到任何成功的方法来为 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
组件上,您可以简单地将剩余的道具传播到 childButtonContainer
中。
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>
);
这是更新的演示。
推荐阅读
- python - 如何使用循环命令切片、创建新的 df 并以特定名称保存?
- r - 是否有从 Excel 电子表格导入现有图形的 R 函数?
- python - 如何使用 BeautifulSoup 显示隐藏的 html 元素?
- python - 试图合并两个图像,但重叠后有可见的线条
- bash - 在 bash 中读取文件并为每一行执行复制和维护序列
- android - 如何在使用 Google Places SDK 时克服重复类问题
- button - Arduino - 按下按钮时如何显示表格?
- python - 试图只抓取每个表格行中的第一个 href
- javascript - 重定向到在文本框中输入的 url
- c++ - 为什么我的 Bowyer-Watson 有时会得到不与超级三角形共享顶点的三角形?