我一直在搜索许多论坛和文章,但没有找到任何成功的方法来为 React 中的函数组件定义接口(interface),该函数组件具有在 defaultProps 中定义的必需属性,而不会引发“属性丢失”Typescript 错误。
我尝试直接在 props 中设置默认值,但它也不起作用。 React 和 Typescript 有什么办法或者 Unresolved 问题吗?
为了查看此问题的实际情况,我提供了 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>;
这是一个工作 demo .
编辑:
根据您的评论,这就是我的推荐。我们可以删除 defaultProps
,并使用 ButtonProps
来定义 ButtonContainer
的类型。在 Button
组件上,您可以简单地将剩余的 props 散布到子 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>
);
这是更新后的demo .
关于javascript - 如何使用 defaultProps 定义 React 函数组件的接口(interface)而不引发丢失类型错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60213218/