React组件传参报错:Type '{ onClose: () => void; }'无法赋值给IntrinsicAttributes
解决TypeScript错误:Property 'onClose' does not exist on type 'IntrinsicAttributes'
这个TypeScript错误的核心原因是你给PropertyTypeComponent传递了onClose属性,但该组件并没有声明接收这个属性的类型。TypeScript对未声明的props会默认归类到IntrinsicAttributes类型中,而这个类型里不存在onClose字段,因此触发了类型不匹配的报错。
修复步骤:
给
PropertyTypeComponent声明props类型
在你的SidebarComponent文件中,为组件定义接收的props类型,明确onClose是一个无参数、无返回值的函数:// 定义组件props的类型 type PropertyTypeProps = { onClose: () => void; }; // 解构接收onClose属性,并指定类型 const PropertyTypeComponent = ({ onClose }: PropertyTypeProps) => { return ( <div className="property-type-container"> {/* 可选:添加触发关闭的元素,比如返回按钮 */} <button onClick={onClose}> <span className="material-symbols-outlined">arrow_back</span> </button> <a href="#">Apartments</a> <a href="#">Villa, Cottages</a> <a href="#">Townhouses</a> <a href="#">Residential Complex</a> <a href="#">Retail</a> </div> ); };在组件内使用
onClose(按需)
既然你传递onClose是为了关闭Drawer,建议在PropertyTypeComponent里添加触发它的交互元素(比如返回按钮),这样用户点击时就能调用父组件的setIsOpen(false)来关闭侧边栏。
临时绕过方案(不推荐)
如果只是临时测试,不想写类型,可以用any绕过类型检查,但这会失去TypeScript的类型安全优势,不建议长期使用:
const PropertyTypeComponent = ({ onClose }: any) => { // ...组件原有内容 };
内容的提问来源于stack exchange,提问作者JoeLoe
相关产品推荐
相关产品推荐

