React+TypeScript中传递带ID的删除函数Props的类型定义问题
解决方案
你的代码存在两个关键问题:onClick的调用方式错误,以及Props类型定义不匹配,下面针对你的需求给出具体修正方案:
问题1:onClick的调用错误
你当前写的 onClick={deleteHandle('id')} 会在组件渲染时立刻执行删除函数,而非点击按钮时触发。必须用箭头函数包裹,实现点击时才传递参数并执行函数。
问题2:类型定义修正
根据你是否需要用到鼠标事件对象,分两种场景处理:
场景1:仅需传递id(无需鼠标事件)
这种是最常见的场景,删除逻辑只需要id参数:
- 子组件Props类型定义:
interface ChildProps { deleteHandle: (id: string) => void; }
- 子组件的按钮写法:
const ChildComponent = ({ deleteHandle }: ChildProps) => { return ( <button onClick={() => deleteHandle('你的目标id')}>Delete</button> ); };
- 父组件的
deleteHandle保持原有写法即可,因为它本来就接收string类型的id参数。
场景2:需要同时传递鼠标事件和id
如果你的删除逻辑需要用到鼠标事件对象(比如阻止默认行为),就需要让函数同时接收两个参数:
- 子组件Props类型定义:
import React from 'react'; interface ChildProps { deleteHandle: (event: React.MouseEvent<HTMLButtonElement>, id: string) => void; }
- 父组件的
deleteHandle修改为接收两个参数:
const deleteHandle = (event: React.MouseEvent<HTMLButtonElement>, id: string) => { // 示例:如果需要阻止默认行为 // event.preventDefault(); dispatch(deleteItem(id)); };
- 子组件的按钮写法:
const ChildComponent = ({ deleteHandle }: ChildProps) => { return ( <button onClick={(e) => deleteHandle(e, '你的目标id')}>Delete</button> ); };
内容的提问来源于stack exchange,提问作者Hakan Gundogdu
相关产品推荐
相关产品推荐

