我有一个带有一些空值的对象文字,我想根据输入列表更改这些值。问题是,尽管在useEffect((中使用预定义的值更新了输入的值,但我无法使用onChange处理程序更改输入。这就是我所拥有的:
const userValues = {
username:'',
city:'',
country:'',
description:''
}
function Comp(){
const [details, setDetails] = useState(userValues)
useEffect(() => {
setUserDetails()
}, [details])
async function setUserDetails() {
setDetails({...details,
username: "username",
country: "country",
city: "city"
})
}
const handleInputChange = (e) =>{
const {name,value} = e.target
setDetails({
...details,
[name]:value
})
<Input fontSize="20px" w="sm" mr={5} fontWeight="bold" textAlign="center"
value={details.username} onChange={(e)=>handleInputChange(e)}/>
}
我还尝试在onChange事件中直接设置值
onChange={(e)=>setDetails({...details,[e.target.name]:e.target.value})}}
但是输入不会从默认值改变。也许有人能给我指明正确的方向。我遵循了本教程https://dev.to/deboragaleano/how-to-handle-multiple-inputs-in-react-55el任何帮助都将不胜感激!
您必须为输入元素设置正确的name
属性,例如:
return (
<Input
name="userName"
value={details.username}
fontSize="20px"
w="sm"
mr={5}
fontWeight="bold"
textAlign="center"
onChange={(e) => handleInputChange(e)}
/>
)
第二个问题是以下影响:
useEffect(() => {
setUserDetails()
}, [details])
每当details
发生变化时,此代码将重置details
您必须删除此效果,或者至少从依赖数组中删除details
,例如:
const [details, setDetails] = useState(() => {
return {
username: "username",
country: "country",
city: "city"
};
});
或
useEffect(() => {
setUserDetails()
}, [])