【问题标题】:React - TypeScript adding undefined to prop even though defaultProps are definedReact - 即使定义了 defaultProps,TypeScript 也会将 undefined 添加到 prop
【发布时间】:2021-03-30 07:18:09
【问题描述】:

为什么会做以下事情:

type Props = {
  name?: string
  age: number
}

const Test = FC<Props> = (props) => {
  return (
    <h1>Hello, {props.name}. You are {props.age} years old.</h1>
  )
}

Test.defaultProps = {
  name: "John"
}

即使namedefaultProps 中定义,当strict 模式设置为true 时,发出name 可能是undefined 的警告。

【问题讨论】:

  • 因为您指定 name 可以在 Props 中未定义
  • 如果你确定你会传​​递名字然后删除?如果不是问我我有一个解决方案
  • @MoshFeu 我认为在FC 中传递Props 的目的是您可以这样做...
  • @GayatriDipali 不一定。 name 有一个默认值。但是如果你删除?,它会在你每次使用组件时要求name prop,这是无效的,因为它有一个默认属性。
  • 不。这意味着name 可以是未定义的,因此代码应该考虑它。您可以删除可选标记 (?),因为知道名称永远不会未定义。

标签: reactjs typescript


【解决方案1】:

Typescript 不会检查 defaultProps 的功能组件。如果你想要一个默认值,你应该使用 ES6 默认值,如:

type Props = {
  name?: string
  age: number
}

const Test: FC<Props> = ({ name = "John" }) => {

}

【讨论】:

【解决方案2】:

你可以做的是:

{props.name ? props.name : "Jhon"}

【讨论】:

  • 这行得通,但首先破坏了使用defaultProps 的全部目的
猜你喜欢
  • 2017-02-19
  • 2022-07-19
  • 2020-06-22
  • 1970-01-01
  • 2020-08-07
  • 2019-02-26
  • 2016-09-20
  • 2019-06-17
  • 1970-01-01
相关资源
最近更新 更多