这是一种反作用形式。 我一直试图在用户提供输入并单击submit按钮后显示Hello{firstName}{lastName}。 但是,它没有正确记录输入,也没有在单击submit按钮后正确显示输入。 请帮帮我!!!
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;
问题是输入框上的事件处理。 在value中,您绑定了fullName.fName和fullName.lName,但在onChange中,您正在更新newName的状态,而fullName的状态只有在单击submit时才会更改。 请更新以下表格代码。 对你应该管用!
<form onSubmit={handleOnSubmit}>
<input
name="fName"
placeholder="First Name"
onChange={handleOnChange}
value={newName.fName}
/>
<input
name="lName"
placeholder="Last Name"
onChange={handleOnChange}
value={newName.lName}
/>
<button type="submit">Submit</button>
</form>
尝试使用这个:我们将创建一个input
自定义钩子。
useInput.js file
//input custom hook
import { useState } from "react";
function useInput(initialValue = "") {
const [value, setValue] = useState(initialValue);
const reset = () => {
setValue(initialValue);
};
const bind = {
value,
onChange: (e) => setValue(e.target.value),
};
return [value, bind, reset];
}
export default useInput;
以下是您如何使用此输入
自定义钩子:
import React from "react";
import useInput from "../hooks/useInput";
function Test() {
const [firstName, bindFirstName, resetFirstName] = useInput("");
const [lastName, bindLastName, resetLastName] = useInput("");
const handleSubmit = (e) => {
e.preventDefault();
alert(`hello ${firstName} ${lastName}`); // you can change this as per your requirement
resetFirstName();
resetLastName();
};
return (
<div>
<form onSubmit={handleSubmit}>
<input type="text" {...bindFirstName} />
<input type="text" {...bindLastName} />
<button value="submit" type="submit">
Submit
</button>
</form>
</div>
);
}
export default Test;