首页 > 解决方案 > 反应组件中的 Typscript 可选参数

问题描述

我有一个像这样的子组件:

export const child= (iconPath?: string) => { /* return and all that good stuff here */ }

像这样渲染我的组件时:

export const parent= () => { 
 return (
  <div>
   <child>
  </div>
 )
}

我越来越 :

类型“{}”不可分配给类型“字符串”。

我在这里做错了什么?

标签: reactjstypescript

解决方案


这是因为 React 期望组件的第一个参数(通常称为props)的类型是 Object 并且默认为{}. 你正试图让它成为一个?string,因此抱怨。

你通常会用 React.FC 定义你的组件

export const child: React.FC<{iconPath?: string}> = (props) => {

  // iconPath will be available as props.iconPath
}

现在你的父组件不应该抱怨


推荐阅读