You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React中如何将App.tsx内的getWords函数传递给WordAddingForm功能组件

步骤1:修改App.tsx组件传参

在App.tsx的渲染部分,正确给子组件传递getWords函数:

// App.tsx 原有return部分修改
return (
  <div>
    <div><WordAddingForm getWords={getWords}/></div>
  </div>
)

你之前两种传参写法的问题说明:第一种props={getWords}是把整个函数挂到了名为props的属性上,子组件需要取props.props才能拿到函数,不符合常规写法;第二种{getWords}是JSX属性简写,等价于getWords={getWords},本身写法没问题,但是子组件没有定义对应的Props类型所以接收不到。

步骤2:给WordAddingForm.tsx定义Props类型并接收参数

在WordAddingForm.tsx开头先定义组件的入参类型,再从组件参数中解构出getWords函数:

// WordAddingForm.tsx 新增Props定义
interface WordAddingFormProps {
  // 声明getWords是无参数、返回Promise的异步函数
  getWords: () => Promise<void>
}

// 给FC泛型传入定义好的Props类型,再解构出getWords
const WordAddingForm: FC<WordAddingFormProps> = ({ getWords }) => {
  // 后续原有代码保持不变

如果运行时报IWord、Context未定义的错误,补充导入对应类型和模块即可。

步骤3:新增单词成功后调用刷新函数

在createWord函数的请求成功逻辑里加上getWords调用,触发列表刷新:

async function createWord(word:string, wordT:string, instance:string, instanceT:string) {
  try {
    const response = await store.createWord(word, wordT, instance, instanceT)
    console.log(response)
    clear()
    // 新增这行,调用父组件传入的刷新方法
    await getWords()
  } catch (e) {
    console.log(e)
  }
}

内容的提问来源于stack exchange,提问作者bluepuper

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.29 07:45:04