javascript - 在 handleChange Typescript 中传递值
问题描述
在我在网上看到的所有示例中,只有事件被传递到 handleChange 并且值被自动使用。但是,我收到一个错误,即找不到值。如何在 handleChange 中使用值?我正在尝试在此处使用 Formik 验证表单。
export default function MyPage() {
const [isSubmitted, setIsSubmitted] = useState(false);
const [isRemoved, setIsRemoved] = useState(false);
const [removeUser] = useMutation<Response>(USER);
let submitForm = (email: string) => {
User({
variables: {
email: email,
},
})
.then(({ data }: ExecutionResult<Response>) => {
if (data !== null && data !== undefined) {
setIsRemoved(true);
}
}) };
const formik = useFormik({
initialValues:{ email: '' },
onSubmit:(values, actions) => {
setTimeout(() => {
alert(JSON.stringify(values, null, 2));
actions.setSubmitting(false);
}, 1000);
},
validationSchema:schema
})
const handleChange = (e: ChangeEvent<HTMLInputElement>)=>{
if (name!== null) && (value!==null){
const {name,value} = event.target;
formik.setFieldValue(name,value);
}
}
return (
<div>
<Form
onSubmit={e => {
e.preventDefault();
submitForm(formik.values.email);
}}>
<div>
<TextField
variant="outlined"
margin="normal"
id="email"
name="email"
helperText={formik.touched.email ? formik.errors.email : ''}
error={formik.touched.email && Boolean(formik.errors.email)}
label="Email"
value={formik.values.email}
//onChange={change.bind(null, 'email')}
onChange={handleChange}
/>
<CustomButton
disabled={!isValid || !formik.values.email}
text={'Remove User'}
/>
</div>
</Form>
</div>
);
}
在这条线上:
const {name,value} = event.target;
即使我已经用 if 语句检查了这个错误,我也会收到这个错误:
Property 'name' does not exist on type 'EventTarget | null'.ts(2339)
解决方案
您正在尝试访问尚未分配的值。首先,声明它们然后尝试访问它们。此外,您正在使用event.target
但您需要使用e.target
,因为您已声明事件,例如:
const handleChange = (e: ChangeEvent<HTMLInputElement>)
因此,函数内部的代码handleChange()
需要更新如下:
const { name,value } = e.target;
if (name && value){
formik.setFieldValue(name, value);
}
推荐阅读
- django - 我可以在 django-models 中添加颜色选择器吗
- reactjs - 使用 Winterfell 响应表单
- firebase - 如何在不使用(已弃用)数据库机密的情况下将 Firebase 集成到 Google Apps 脚本中
- asp.net-core - 在具有 EF Core 迁移的 Net Core 类库上使用 settings.json
- matlab - 如何在 MATLAB 中调整条形绝对宽度
- c++ - Qt 对于我的带宽上限来说太大了。我的替代方案是什么?
- uitableview - 设置 UITableViewCellAccessory 的左 X 位置
- dask - 无法通过 SSH 启动 dask 集群
- appium - 如何使用 Appium 运行需要两台设备的测试
- java - XWPFRun 生成运行并修剪空格