reactjs - 反应组件中的 Typscript 可选参数
问题描述
我有一个像这样的子组件:
export const child= (iconPath?: string) => { /* return and all that good stuff here */ }
像这样渲染我的组件时:
export const parent= () => {
return (
<div>
<child>
</div>
)
}
我越来越 :
类型“{}”不可分配给类型“字符串”。
我在这里做错了什么?
解决方案
这是因为 React 期望组件的第一个参数(通常称为props
)的类型是 Object 并且默认为{}
. 你正试图让它成为一个?string
,因此抱怨。
你通常会用 React.FC 定义你的组件
export const child: React.FC<{iconPath?: string}> = (props) => {
// iconPath will be available as props.iconPath
}
现在你的父组件不应该抱怨
推荐阅读
- azure-devops - Azure DevOPS:重新部署旧版本(仅一个阶段)未部署旧更改
- react-native - 应用程序进入后台时动画平面列表插值问题
- python - 在 python 循环中运行 bash 命令
- python-3.x - 在训练顺序张量流和 keras 模型中记录时间步长
- mysql - MySQL - 选择匹配所有值的记录
- c - 使用一个目标文件,该目标文件正在使用新内核上的新内核删除的内核函数?
- python - 根据 Pandas 中列的内容将列拆分为多列
- javascript - Google Chart not 100% of div width - 包含事件侦听器以从代理表重绘图表
- javascript - Javascript cloneNode innerText 不读取
为 \n - macos - DriverKit 是否适用于自定义 USB 设备来控制麦克风音量(无流)?