gpt4 book ai didi

reactjs - react-hook-form - 无法将表单数据传递给父组件

转载 作者:行者123 更新时间:2023-12-04 15:23:47 25 4
gpt4 key购买 nike

我正在使用 react 钩形并尝试将数据从表单传递到其父级。
为此,我试图通过回调传递数据,但它不起作用。
当我 console.log 数据在父组件内,我未定义。
父组件

import React from 'react';
import InputForm from './InputForm';

const App = (data) => {
const onFormSubmit = () => {
console.log(data.name);
};

return (
<div className='App'>
<InputForm onceSubmited={() => onFormSubmit()} />
</div>
);
};

export default App;
子组件
import React from 'react';
import { useForm } from 'react-hook-form';

const InputForm = ({ onceSubmited }) => {
const { register, handleSubmit } = useForm();

const onSubmit = (data) => {
console.log(data);
onceSubmited(data);
};

return (
<>
<form onSubmit={handleSubmit(onSubmit)}>
<input
type='text'
name='name'
ref={register}
/>

<input
type='email'
name='email'
ref={register}
/>

<button type='submit'>
Submit
</button>
</Form>
</>
);
};

export default InputForm;

最佳答案

您需要在箭头函数中传递参数。这应该使它工作:

import React from 'react';
import InputForm from './InputForm';

const App = () => {
const onFormSubmit = (data) => {
console.log(data.name);
};

return (
<div className='App'>
<InputForm onceSubmited={(data) => onFormSubmit(data)} />
</div>
);
};

export default App;

关于reactjs - react-hook-form - 无法将表单数据传递给父组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62735921/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com