首页 > 解决方案 > 如何使用 defaultProps 为 React 函数组件定义接口而不抛出缺少类型错误?

问题描述

我一直在搜索许多论坛和文章,但没有找到任何成功的方法来为 React 中的函数组件定义接口,该接口具有在 defaultProps 中定义的所需属性,而不会引发“缺少属性”Typescript 错误。

我尝试直接在 props 中设置默认值,但它也不起作用。在 React 和 Typescript 中有什么方法或未解决的问题吗?

为了看到这个问题的实际效果,我提供了 CodeSandbox 项目。

编辑 misty-pine-rtdl8

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>
);

标签: javascriptreactjstypescripttypescript-typings

解决方案


由于colorButtonProps类型的唯一属性,您可以使用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>
);

这是更新的演示


推荐阅读