react-8 自定义组件如何向下传递表单数据
dearweb
发布:2023-03-31 09:41:03阅读:
以下是一个简单的实例,展示如何在 React 中自定义组件中处理表单数据并将其传递给父组件:
import React, { useState } from 'react';
interface MyCustomComponentProps {
onChange: (value: string) => void;
}
const MyCustomComponent: React.FC<MyCustomComponentProps> = ({ onChange }) => {
const [inputValue, setInputValue] = useState('');
const handleInputChange = (event: React.ChangeEvent<HTMLInputElement>) => {
const value = event.target.value;
setInputValue(value);
onChange(value);
}
return (
<input type="text" value={inputValue} onChange={handleInputChange} />
);
}
interface MyFormProps {
onSubmit: (formData: any) => void;
}
const MyForm: React.FC<MyFormProps> = ({ onSubmit }) => {
const [formValue, setFormValue] = useState('');
const handleFormSubmit = (event: React.FormEvent<HTMLFormElement>) => {
event.preventDefault();
onSubmit(formValue);
}
const handleCustomComponentChange = (value: string) => {
setFormValue(value);
}
return (
<form onSubmit={handleFormSubmit}>
<MyCustomComponent onChange={handleCustomComponentChange} />
<button type="submit">Submit</button>
</form>
);
}
export default MyForm;在上面的代码中,`MyCustomComponent` 是一个自定义组件,它接收一个 `onChange` 属性,该属性是一个回调函数,用于在输入框的值发生变化时将新值传递给父组件。在 `MyCustomComponent` 中,我们使用 `useState` 钩子来跟踪输入框的值,并在输入框的值发生变化时调用 `onChange` 回调函数。
`MyForm` 是一个包含自定义组件的表单,它接收一个 `onSubmit` 属性,该属性是一个回调函数,用于在表单提交时将表单数据传递给父组件。在 `MyForm` 中,我们使用 `useState` 钩子来跟踪表单的值,并在表单提交时调用 `onSubmit` 回调函数。我们还定义了一个 `handleCustomComponentChange` 回调函数,用于将自定义组件中的值传递给父组件。
最后,我们在 `MyForm` 中渲染了自定义组件和一个提交按钮,并将 `handleCustomComponentChange` 传递给自定义组件的 `onChange` 属性,以便在自定义组件中的值发生变化时将其传递给父组件。当用户提交表单时,我们调用 `handleFormSubmit` 回调函数,并将表单数据传递给父组件。
小礼物走一波,支持作者
赏还没有人赞赏,支持一波吧