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,所以是的