我有一个React表单,其中我无法控制使用useState钩子输入的复选框的值。我对其他输入没有这个问题。
我无法将复选框输入值传递给AuthData对象。当您点击";登录";按钮,控制台应显示一个AuthData对象,该对象包含字段{login:",password:",isRemember:"}
import React from 'react'
import { useState } from 'react'
export const AuthForm = ({ handlers }) => {
const [authData, setAuthData] = useState({ login: '', password: '', isRemember: '' })
const changeValue = (event) => {
const { id, value } = event.target
setAuthData((prevAuthData) => ({ ...prevAuthData, [id]: value }))
}
const signIn = () => {
console.log(authData)
}
return (
<form onSubmit={(e) => e.preventDefault()}>
<input
type="text"
id="login"
placeholder="Login/E-mail/Phone"
value={authData.login}
onChange={changeValue}
/>
<input
type="password"
id="password"
placeholder="Password"
value={authData.password}
onChange={changeValue}
/>
<input
type="checkbox"
id="isRemember"
value={authData.isRemember}
onChange={changeValue}
/>
<button onClick={signIn}>Sign in</button>
</form>
)
}
更改输入值时,必须将其值传递给authValue对象。用";登录";以及";密码";输入它们的值进入authValue对象;is记住"输入这不起作用。复选框输入的值以某种方式不会进入authValue对象。
您可以检查输入type
,并从事件对象中获得checkbox
的checked
值,如下所示
const changeValue = (event) => {
let { id, value, type, checked="" } = event.target;
if (type === "checkbox") {
value = checked;
}
setAuthData((prevAuthData) => ({ ...prevAuthData, [id]: value }));
};
您必须在复选框输入中使用checked
属性。
使用了value属性,但您必须对其进行修改,以确保它将true
或false
发送到状态对象
我添加了一个片段来回应你的评论。
const {useState} = React
const AuthForm = ({ handlers }) => {
const [authData, setAuthData] = useState({ login: '', password: '', isRemember: false })
const changeValue = (event) => {
const { id, value } = event.target
setAuthData((prevAuthData) => ({ ...prevAuthData, [id]: value }))
}
const changeCheckbox = () => {
setAuthData((prevAuthData) => ({ ...prevAuthData, isRemember: !prevAuthData.isRemember }))
}
const signIn = () => {
console.log(authData)
}
console.log(authData);
return (
<form onSubmit={(e) => e.preventDefault()}>
<input
type="text"
id="login"
placeholder="Login/E-mail/Phone"
value={authData.login}
onChange={changeValue}
/>
<input
type="password"
id="password"
placeholder="Password"
value={authData.password}
onChange={changeValue}
/>
<input
type="checkbox"
id="isRemember"
checked={authData.isRemember}
onChange={changeCheckbox}
/>
<button onClick={signIn}>Sign in</button>
</form>
)
}
// Render it
ReactDOM.createRoot(
document.getElementById("root")
).render(
<AuthForm />
);
<div id="root"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/18.1.0/umd/react.development.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/18.1.0/umd/react-dom.development.js"></script>