IT虾米网

reactjs之如何使用 onSubmit 输入 Form 组件

third_qq_acbf90bbd2dede1d 2026年10月07日 程序员 98 0

我有自己的Form我想将其与 Parent Component 分开。

const Form: React.FC<any> = ({ children, handleFormSubmit }) => ( 
  <form onSubmit={handleFormSubmit}>{children}</form> 
); 

Parent Component

const ParentComponent = () => { 
... 
 
const handleFormSubmit = (event: React.FormEvent<HTMLFormElement>) => { 
    event.preventDefault(); 
    publishReview(review).then(() => setReview(initialReviewState)); 
  }; 
 
return ( 
 <Form onSubmit={handleFormSubmit}> 
... 
</Form> 
)} 

我以为handleFormSubmit将从其声明 const handleFormSubmit = (event: React.FormEvent<HTMLFormElement>) 获取类型.

但事实并非如此

我尝试构建一个界面,甚至使用 any类型:

interface FormProps { 
  handleFormSubmit: any 
} 
const Form: React.FC<FormProps>= ({ children, handleFormSubmit }) => ( 
  <form onSubmit={handleFormSubmit}>{children}</form> 
); 

但它给出了以下错误:

const Form: React.FunctionComponent<FormProps> 
Type '{ children: Element; onSubmit: (event: FormEvent<HTMLFormElement>) => void; }' is not assignable to type 'IntrinsicAttributes & FormProps & { children?: ReactNode; }'. 
  Property 'onSubmit' does not exist on type 'IntrinsicAttributes & FormProps & { children?: ReactNode; }'. 

请您参考如下方法:

这对我有用。只是根据您的猜测进行猜测。谢谢!

handlePostForm = (e: React.FormEvent) => { 


评论关闭
IT虾米网

微信公众号号:IT虾米 (左侧二维码扫一扫)欢迎添加!