Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/typescript/9.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/image/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Reactjs 使用TypeScript对函数组件属性默认值作出反应_Reactjs_Typescript - Fatal编程技术网

Reactjs 使用TypeScript对函数组件属性默认值作出反应

Reactjs 使用TypeScript对函数组件属性默认值作出反应,reactjs,typescript,Reactjs,Typescript,我在React函数组件和默认所需道具方面遇到问题 以下是组件: type Props = { message: string }; function Greeting({ message = "How are you?" }: Props) { return <p>{message}</p>; } 但是,TypeScript引发类型错误属性“message”在类型“{}”中丢失,但在类型“Props”中是必需的: 下面是代码沙盒中的问题: 我不确定我是做错了什么,

我在React函数组件和默认所需道具方面遇到问题

以下是组件:

type Props = { message: string };
function Greeting({ message = "How are you?" }: Props) {
  return <p>{message}</p>;
}
但是,TypeScript引发类型错误属性“message”在类型“{}”中丢失,但在类型“Props”中是必需的:

下面是代码沙盒中的问题:


我不确定我是做错了什么,还是这是打字稿中的一个小故障?任何帮助都将不胜感激。

您的
道具
类型定义具有必需的参数
消息
,但是您将其视为可选参数。这也会在您收到的错误消息中引用

  • 类型“
    {}
    ”中缺少属性“
    message
    ”,但类型“
    Props
    ”中需要属性“

  • 将错误消息理解为-您的
    类型道具
    具有所需的
    消息
    属性,但是,您提供的类型
    {}缺少该属性(将
    {}
    读取为未提供属性)


将定义更改为以下方式:

type Props = {
   message?: string; //< note the '?' at the end of property
};
类型道具={
消息?:字符串;//<注意属性末尾的“?”
};

现在,如果返回的组件没有特定的
消息
道具,那么它将默认为
“你好吗?”

这需要作为示例问题使用。问得很好。
属性“message”在类型“{}”中缺失,但在类型“Props”中是必需的。ts
它表示您需要Props类型。这就是为什么typescript为此尖叫:)只需更改类型道具,如
message?:string
。此外,添加JavaScript标记可能是个好主意。
type Props = {
   message?: string; //< note the '?' at the end of property
};