首页 > 解决方案 > 功能组件的 props 的默认值有什么问题

问题描述

我不知道,在打字稿中为功能组件编写 props 的默认值有什么问题:

这是我的代码:

Copywrite.tsx

interface Props {
    siteName: string
    webUrl: string
}

export const Copyright: React.FC<Props> = (
    props: Props = { siteName: 'myWeb', webUrl: 'http://localhost:3000' }
       ) => {
              return (
                 <div>
                    <p>{props.siteName}</p>
                    <p>{props.webUrl}</p>
                 </div>
               )
       }

App.tsx

const App = (props: Props) => {
return (
    <>
      <Copyright />
    </>
    )
}

export default App

我得到了错误:Type '{}' is missing the following properties from type 'Props': siteName, webUrl TS2739

但是,当我将Props界面设置为:

interface Props {
    siteName?: string
    webUrl?: string
}

然后,我App.tsx不会在我的网页上显示道具值。

我的代码有什么问题?

非常感谢您的帮助!

标签: reactjstypescript

解决方案


问题是它props实际上并不是空的:React 为它提供了一个空对象。

您可以解构并为每个道具设置默认值,如下所示:


interface Props {
    siteName?: string
    webUrl?: string
}

export const Copyright: React.FC<Props> = (
  { siteName = 'myWeb', webUrl = 'http://localhost:3000' }
) => {
  return (
    <div>
      <p>{siteName}</p>
      <p>{webUrl}</p>
    </div>
  )
}

推荐阅读