这是一个 React 表单。在用户提供输入并单击提交按钮后,我一直在尝试显示 Hello {firstName} {lastName} 。但是,它没有正确记录输入,并且在单击提交按钮后没有正确显示。请帮忙!!!
import React, { useState } from 'react';
function App() {
const [newName, setNewName] = useState({
fName: '',
lName: ''
});
const [fullName, setFullName] = useState(newName);
function handleOnSubmit(event) {
console.log(newName);
setFullName(newName);
event.preventDefault();
}
function handleOnChange(event) {
console.log(newName);
var { value, name } = event.target;
setNewName((prevValue) => {
if (name === 'fName')
return {
fName: value,
lName: prevValue.lName
};
else
return {
fName: prevValue.fName,
lName: value
};
});
}
return (
<div className='container'>
<h1>
Hello {fullName.fName} {fullName.lName}
</h1>
<form onSubmit={handleOnSubmit}>
<input
name='fName'
placeholder='First Name'
onChange={handleOnChange}
value={fullName.fName}
/>
<input
name='lName'
placeholder='Last Name'
onChange={handleOnChange}
value={fullName.lName}
/>
<button type='submit'>Submit</button>
</form>
</div>
);
}
export default App;