Typescript环境下React父子组件函数如何正确传递参数?
问题原因及解决方法
你犯了3处核心错误,按顺序修正即可:
- 子组件的Props类型定义与父组件传入的函数实际形态完全不匹配
你定义的getNewVerseFunc类型为仅接收点击事件、返回字符串的函数,但父组件实际传入的是接收两个字符串参数、无返回值的异步函数,类型不匹配会直接导致参数传递异常,同时TS也会抛出隐式类型错误。
- 子组件的Props类型定义与父组件传入的函数实际形态完全不匹配
bind方法的传参顺序错误Function.prototype.bind的第一个参数是绑定的this指向,后续参数才是传入目标函数的入参,你直接把name作为第一个参数传入,会导致this指向被修改为name,目标函数收到的第一个参数就变成了点击事件对象,而非你期望的name。
- 子组件未声明
name、id对应的Props
你在子组件中直接使用的name和id变量未通过Props传入,属于未定义变量,自然无法传递正确值。
- 子组件未声明
修正后的代码
1. 子组件 Button.tsx
type ButtonProps = { getNewVerseFunc: (name: string, id: string) => Promise<void>; name: string; id: string; }; const Button = ({ getNewVerseFunc, name, id }: ButtonProps) => { return ( <div> <div // 更推荐用箭头函数包裹,比bind可读性更高 onClick={() => getNewVerseFunc(name, id)} // 如果坚持用bind需要把第一个参数设为null/undefined // onClick={getNewVerseFunc.bind(null, name, id)} > 点击按钮 </div> </div> ); };
2. 父组件 ParentDiv.tsx
// 补充函数闭合、返回值处理,你原来的代码缺少函数闭合括号 const getNewVerseFunc = async (name: string, id: string) => { const requ = await fetch( `https://api.scripture.api.bible/${name}/${id}`, { method: "GET", headers: { "api-key": bibleApi, }, } ); // 按需处理返回结果即可 const res = await requ.json(); console.log(res); }; // 调用子组件时需要把name、id也作为Props传入 <Button getNewVerseFunc={getNewVerseFunc} name="你要传入的name值" id="你要传入的id值" />
内容的提问来源于stack exchange,提问作者D. R.
相关产品推荐
相关产品推荐

