React TS传props报{walletAddress:string}无法赋值为string解决方法
错误原因
React函数组件的第一个入参统一为props对象,所有在JSX标签上传递的属性,都会被封装为这个对象的键值对传入组件,不会单独拆分单个属性作为入参。
你当前的代码将组件入参直接标注为string类型,等于告诉TypeScript该组件接收的props整体是字符串格式,但实际传入的是结构为{ walletAddress: string }的对象,因此触发ts(2322)类型不匹配错误,你打印入参看到对象结构也和这个逻辑完全一致。
修复方法
父组件传参代码无需修改,只需要调整Address组件的定义即可,两种常用写法如下:
- 普通函数组件写法(推荐)
// 定义组件接收的props类型 type AddressProps = { walletAddress: string } // 从props对象中解构出需要使用的字段 const Address = ({ walletAddress }: AddressProps) => { return ( <div className="mb-10">{walletAddress}</div> ) }
- 使用React内置FC泛型写法
import type { FC } from 'react' type AddressProps = { walletAddress: string } const Address: FC<AddressProps> = ({ walletAddress }) => { return ( <div className="mb-10">{walletAddress}</div> ) }
注意:只要是通过JSX标签形式使用的组件,永远不要给入参直接标注string、number这类基础类型,props一定是对象结构,所有传入的属性都要在该对象的类型定义中声明。
内容的提问来源于stack exchange,提问作者plutownium
相关产品推荐
相关产品推荐

