我试图传递道具
<Mycomp
deleteAcc={handleDelete(accountId)}
/>
到另一个组件。我写的道具就像
interface AccProps {
deleteAcc: () => void;
}
并像调用这样的函数
deleteAcc()
但我收到以下错误
Type 'void' is not assignable to type '() => void'
不确定我在这里错过了什么。
答案 0 :(得分:0)
很可能是因为 handleDelete
函数的返回值类型是 void
,而您传递了 handleDelete
的返回值。而 deleteAcc
需要一个 () => void
类型的函数。
试试:
<Mycomp deleteAcc={() => handleDelete(accountId)}/>
答案 1 :(得分:0)
当您将 handleDelete(accountId)
作为 prop 传递时,该函数会立即被调用,其返回值(在本例中为 void
)是作为 prop 传递的值。
如果函数必须接受这个特定参数,请将其作为回调发送:
<Mycomp deleteAcc={() => handleDelete(accountId)} />
由于 handleDelete(accountId)
返回 void
,此回调类型为 () => void
,因此适合 prop 类型。
如果函数不需要接受参数,可以按名称发送:
<Mycomp deleteAcc={handleDelete} />
通常一个好主意是在组件中创建一个唯一的包装函数并按名称发送它,例如:
const wrapper = () => {
handleDelete(accountId);
};
<Mycomp deleteAcc={wrapper} />