programing

onSubmit을 사용하여 양식 구성 요소를 입력하는 방법

css3 2023. 3. 6. 21:23

onSubmit을 사용하여 양식 구성 요소를 입력하는 방법

나는 내 것이 있다.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) => {

양식 요소의 유형을 지정해야 합니다.예를 들어, 양식에 ID가 있는 입력이 있다고 가정해 보겠습니다.yourInputName:

<form onSubmit={handleSubmit}>
  <div>
    <label htmlFor="yourInputName">Username:</label>
    <input id="yourInputName" type="text" />
  </div>
  <button type="submit">Submit</button>
</form>

고객님의 고객명handleSubmit, 의 타입을 지정할 필요가 있습니다.event.currentTarget폼 태그에는 다음 유형이 있습니다.HTMLFormElement재산을 가지고elements의 한 종류입니다.HTMLFormControlsCollection다만, TS에 입력 내용을 전달하기 위해서, 이것을 무효로 할 수 있습니다.를 확장하기 위한 인터페이스를 만듭니다.HTMLFormControlsCollection필드의 유형을 지정한 후 커스텀인터페이스를 사용하여 의 요소 속성을 덮어씁니다.HTMLFormElement.

interface FormElements extends HTMLFormControlsCollection {
    yourInputName: HTMLInputElement
}

interface YourFormElement extends HTMLFormElement {
   readonly elements: FormElements
}

그런 다음 새로운 유형을 처리 기능에 전달합니다.

const handleFormSubmit = (e: React.FormEvent<YourFormElement>) => {}

이제 필드의 값에 액세스할 수 있으며, 타이프스크립트가 무엇인지 알 수 있습니다.

const handleFormSubmit = (e: React.FormEvent<YourFormElement>) => {
    e.preventDefault();
    console.log(e.currentTarget.elements.yourInputName.value)
}

위에서 맴돌면valueTS에 데이터 타입이 다음과 같은 메시지가 표시됩니다.HTMLInputElement.value: string에서 지정한 바와 같이FormElements인터페이스입니다.

  const handleSubmit = (event: FormEvent<HTMLFormElement>) => {

react에 제어되지 않은 형식이 있는 경우(I used MUI field):

<form onSubmit={handleSubmit}>
          <TextField
            error={isError}
            helperText={isError ? 'Incorrect entry.' : ''}
            margin="normal"
            color="success"
            label="Name and surname"
            id="nameSurname"
            size="small"
          /></form>

다음과 같이 할 수 있습니다.

const handleSubmit = (e: SyntheticEvent) => {
e.preventDefault();
const target = e.target as typeof e.target & {
  nameSurname: { value: string };
  //password: { value: string };
};
const nameSurname = target.nameSurname.value;
console.log(`nameSurname`, nameSurname);

}; 여기서 영감을 얻었다.

소품 이름을 잘못 아신 것 같군요미스매치가 보이나요?

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

당신의.Form컴포넌트는 다음과 같은 이름의 프로펠러가 있습니다.handleFormSubmit라고 하는 이름의 소품으로 호출하고 있습니다.onSubmit대신.

둘 다 일치하도록 둘 중 하나의 이름을 변경해야 합니다.어느 쪽인가의 콜<Form handleFormSubmit={handleFormSubmit}>소품을 바꾸거나Form소품 이름을 붙이도록 구성 요소onSubmit.


소품 이름을 다음과 같이 바꾸면 다음과 같습니다.onSubmit대신 적절한 활자를 붙입니다.any.

interface FormProps {
    onSubmit: React.FormEventHandler;
}

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

를 변경할 필요가 없습니다.ParentComponent정의하면Form이것처럼.

이보가 쓴 것처럼, 하지만 만약 당신이 그것을 제대로 타이핑하고 싶다면type:

type FormElements = Readonly<
  {
    yourInputName: HTMLInputElement
  } & HTMLFormControlsCollection
>;

type YourFormElement = Readonly<
  {
    elements: FormElements;
  } & HTMLFormElement
>;

언급URL : https://stackoverflow.com/questions/56322667/how-to-type-a-form-component-with-onsubmit