【问题标题】:React function component prop default with TypeScriptReact 函数组件 prop 默认使用 TypeScript
【发布时间】:2020-05-27 06:17:59
【问题描述】:

我在使用 React 函数组件和默认所需的道具时遇到问题。

这是组件:

type Props = { message: string };
function Greeting({ message = "How are you?" }: Props) {
  return <p>{message}</p>;
}

我应该能够在不传递message 属性的情况下使用它:

<Greeting />

但是,TypeScript 会引发类型错误类型“{}”中缺少属性“消息”,但类型“道具”中是必需的:

这是 CodeSandbox 中的问题:https://codesandbox.io/s/still-microservice-lp7b5?fontsize=14&hidenavigation=1&theme=dark

我不确定我做错了什么,或者这是否是 TypeScript 中的一个小故障?任何帮助将不胜感激。

【问题讨论】:

  • 这需要在某处用作示例问题。问得很好。
  • Property 'message' is missing in type '{}' but required in type 'Props'.ts 它说你有需要的道具类型。这就是为什么打字稿为此尖叫的原因 :) 只需像这样message?:string 更改类型道具。
  • 另外,添加 JavaScript 标记可能是个好主意。

标签: reactjs typescript


【解决方案1】:

您的Props 类型定义具有message 的必需 参数,但是您将其视为可选参数。您收到的错误消息中也提到了这一点

  • “{}”类型中缺少属性“message”,但在“Props”类型中是必需的

  • 1234563

将定义改为如下方式:

type Props = {
   message?: string; //< note the '?' at the end of property
};

现在如果返回的组件没有特定的message prop,它将默认为"How are you?"

【讨论】:

    猜你喜欢
    • 2018-04-12
    • 1970-01-01
    • 2021-11-25
    • 2016-09-13
    • 1970-01-01
    • 2019-12-27
    • 2020-10-30
    • 2020-02-26
    • 2020-11-07
    相关资源
    最近更新 更多