Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/typescript/8.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Reactjs react组件中的Typscript可选参数_Reactjs_Typescript - Fatal编程技术网

Reactjs react组件中的Typscript可选参数

Reactjs react组件中的Typscript可选参数,reactjs,typescript,Reactjs,Typescript,我有一个子组件,如下所示: export const child= (iconPath?: string) => { /* return and all that good stuff here */ } export const parent= () => { return ( <div> <child> </div> ) } 这样渲染我的组件时: export const child= (iconPath?: strin

我有一个子组件,如下所示:

export const child= (iconPath?: string) => { /* return and all that good stuff here */ }
export const parent= () => { 
 return (
  <div>
   <child>
  </div>
 )
}
这样渲染我的组件时:

export const child= (iconPath?: string) => { /* return and all that good stuff here */ }
export const parent= () => { 
 return (
  <div>
   <child>
  </div>
 )
}
我得到:

类型“{}”不可分配给类型“string”


我到底做错了什么

Its因为React期望组件的第一个参数(通常称为props)的类型为对象,并且默认为{}。你是想把它变成一根绳子,所以抱怨

通常使用React.FC定义组件

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

  // iconPath will be available as props.iconPath
}

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

或者,您可以定义道具的类型。像这样:

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

您应该只能在.tsx文件中编写jsx,所以是的