reactjs - 功能组件的 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
不会在我的网页上显示道具值。
我的代码有什么问题?
非常感谢您的帮助!
解决方案
问题是它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>
)
}
推荐阅读
- amazon-web-services - aws_route_table_association 不适用于所有私有 * 子网 - terraform
- sql - 将军用时间转换为标准时间误差
- r - 如何删除R中以下数字中左起第二个(2)和右起第五个(0)?例如:3255103161
- html - 响应式图像滑块不起作用
- point-cloud-library - SIFT3D 可以在 XYZ 和 XYZRGB 格式的点云上工作吗?
- visual-studio - TypeScript 和调整值(等待刷新,直到文件编译完成)
- php - 使用 php 重命名文件显示权限被拒绝
- javascript - 如何对嵌套对象映射进行排序并根据排序有效地分配值?
- intellij-idea-2016 - Intellij 启动错误:找不到主类 com/intellij/idea/Main
- python - DBSCAN 用于经纬度点和标称特征