[英]How to pass function as a prop in react typescript
I am learning typescript with react and I occurred problem.我正在用 React 学习 typescript,我遇到了问题。 I tried to pass function as a prop from my App component to child component named DataForm.我试图将 function 作为道具从我的 App 组件传递给名为 DataForm 的子组件。
but I got an error:但我得到一个错误:
Type '(f: any) => any' is not assignable to type '() => void'.类型 '(f: any) => any' 不可分配给类型 '() => void'。
Parameter 'f' implicitly has an 'any' type.参数“f”隐式具有“任何”类型。
And this is my code这是我的代码
App.tsx应用程序.tsx
import React from 'react'; import './App.css'; import DataForm from './components/form'; export const Data = { name: "", country: "", age:"", adress:"" } function App() { const generateCard = ()=>{ console.log(" generateCard runned") } return ( <> <h1>Human Card Generator</h1> <DataForm createCard = { generateCard }/> </> ); } export default App;
components/form.tsx组件/form.tsx
import React from 'react' import { Data } from '../App' import 'bootstrap'; interface dataFormProps{ createCard: ()=>void } export default function DataForm({ createCard = f => f }: dataFormProps){ const dataProceed = (e: any) =>{ Data.name = (document.getElementById('name') as HTMLInputElement).value; Data.country = (document.getElementById('country') as HTMLInputElement).value; Data.age = (document.getElementById('age') as HTMLInputElement).value; Data.adress = (document.getElementById('adress') as HTMLInputElement).value; createCard(); } return( <form onSubmit = { dataProceed }> <input type="text" id = "name" /> <input type="text" id = "country" /> <input type="number" id="age" /> <input type="text" id = "adress"/> <button type="submit">stwórz kartę</button> </form> ) }
The issue isn't when passing the function, it's when destructuring the props and providing a default function:问题不在于传递 function 时,而是在解构道具并提供默认值 function 时:
{ createCard = f => f }: dataFormProps
This code indicates that createCard
should be a function which accepts a parameter and returns a value.此代码表明createCard
应该是一个 function,它接受一个参数并返回一个值。 Which it doesn't:它没有:
createCard: ()=>void
Make the default parameter match the signature:使默认参数与签名匹配:
{ createCard = () => {} }: dataFormProps
default function createCard
should has type () => void
.默认 function createCard
应该有类型() => void
。 So just update like this:所以只需像这样更新:
DataForm({ createCard = () => {} }: dataFormProps)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.