我有一个React表单,它有两个提交按钮,使用Axios可以访问两个不同的端点。
当我试图获取表单提交者的值(到达哪个端点(时,当使用React with TS时,我会得到以下错误。
属性"submitter"在类型"Event"上不存在
我的代码如下:
async function handleSubmit(e: React.SyntheticEvent<HTMLFormElement>) {
const submitter = e.nativeEvent.submitter.value;
e.preventDefault();
checkedBox.length > 0 &&
(await axios
.post(
`${process.env.REACT_APP_BACKEND_BASE}/update${submitter}tasks`,
checkedBox
)
.then((response) => {
if (response.status === 200) {
setForceUpdate((current) => (current += 1));
}
})
.catch((error) => {
console.log(error);
}));
}
如果我将函数类型更改为(e:React.BaseSyntheticEvent(,onSubmit属性上会弹出另一个错误。
<form onSubmit={handleSubmit}>
错误为:
类型'(e:BaseSyntheticEvent<HTMLFormElement,any,any>(=>Promise"不可分配给类型"FormEventHandler"。参数"e"one_answers"event"的类型不兼容。类型"FormEvent"不可分配给类型"BaseSyntheticEvent<HTMLFormElement,任意,任意>'。属性"nativeEvent"的类型不兼容。类型"Event"缺少类型"HTMLFormElement"中的以下属性:acceptCharset、action、autocomplete、elements和294 more.ts(2322(
尝试使用SyntheticEvent
和SubmitEvent
const handleSubmit = (event: SyntheticEvent<HTMLFormElement, SubmitEvent>) => {}
解释
当我们使用FormEvent<HTMLFormElement>
时,它扩展为:
FormEvent<T = Element>
SyntheticEvent<T = Element, E = Event> // notice it hardcodes Event
BaseSyntheticEvent<E, EventTarget & T, EventTarget> // also hardcodes EventTarget
target: EventTarget // hardcoded
nativeEvent: Event // hardcoded
currentTarget: HTMLFormElement & EventTarget
因此,不使用FormEvent
,而是使用SyntheticEvent
,结果是:
SyntheticEvent<T = HTMLFormElement, E = SubmitEvent>
BaseSyntheticEvent<E, EventTarget & T, EventTarget>
target: HTMLFormElement // 🎉
nativeEvent: SubmitEvent // 🎉
currentTarget: HTMLFormElement & EventTarget
编码快乐!
聚会可能有点晚,但这对我在TypeScript:中有效
const handleSubmit = (event: SyntheticEvent) => {
const eventSubmitter = (event.nativeEvent as SubmitEvent).submitter;
}
如果您使用的是表单:
转换此
async function handleSubmit(e: React.SyntheticEvent<HTMLFormElement>) {
const submitter = e.nativeEvent.submitter.value;
}
到此
async function handleSubmit(e: FormEvent) {
const submitter = e.nativeEvent.submitter.value;
}
此外,您可能需要执行以下操作:e.nativeEvent?.submitter.value
我通过删除form元素来修复它,因为它对axios毫无用处&使用onClicks将所有按钮转换为普通按钮,从而触发handleSubmit函数。
我有它如下:
async function handleSubmit(e: React.SyntheticEvent<HTMLButtonElement>) {
const submitter = (e.target as HTMLButtonElement).value;
checkedBox.length > 0 &&
(await axios
.post(
`${process.env.REACT_APP_BACKEND_BASE}/update${submitter}tasks`,
checkedBox
)
.then((response) => {
if (response.status === 200) {
setForceUpdate((current) => (current += 1));
}
})
.catch((error) => {
console.log(error);
}));
}
按钮如下:
<Button
type="button"
name="submit"
value="delete"
variant="outline-info"
onClick={handleSubmit}
size="lg"
className="text-center font-main-color"
> Button </Button>