React Typescript 输入 onChange 事件类型?
React Typescript input onChange event type?
我正在尝试从输入元素中获取文本,将其设置为状态,然后将其呈现回输入框中。但是我认为我的事件类型是错误的?我在网上搜索并尝试实施许多解决方案,但 none 到目前为止都有效。感谢任何帮助。
我的组件:
import React, { ChangeEvent, ChangeEventHandler, useState } from "react";
export default function Unidirectionflow() {
const [state4, setState4] = useState("");
const [state5, setState5] = useState("");
let handleChange4 = (e: React.FormEvent<HTMLInputElement>): void => {
setState3((e.target as HTMLInputElement).value);
};
let handleChange5 = (event: ChangeEvent<HTMLInputElement>) => {
setState5(event.currentTarget.value);
};
return (
<main>
<input type="text" value={state4} onChange={() => handleChange4} />
<input type="text" value={state5} onChange={() => handleChange5} />
</main>
);
}
https://react-typescript-cheatsheet.netlify.app/docs/basic/getting-started/forms_and_events/
您在调用函数时忘记传递event
试试这个
onChange={(e) => handleChange(e)}
或者
onChange={handleChange}
代码沙箱 => https://codesandbox.io/s/dreamy-pateu-1mc6j?file=/src/App.tsx
你可以这样做
export default function Unidirectionflow() {
const [states, setStates] = useState({
state3:'',
state4:''
})
const handleChange = (
e: React.ChangeEvent<HTMLTextAreaElement | HTMLInputElement>
) => {
setStates({
...states,
[e.target.name]: e.target.value.trim(),
});
};
return (
<main>
<input type="text" name="state3" value={states.state3} onChange={handleChange} />
<input type="text" name="state4" value={states.state4} onChange={handleChange} />
</main>
);
};
onChange={handleChange}
看看能不能帮到你!
我正在尝试从输入元素中获取文本,将其设置为状态,然后将其呈现回输入框中。但是我认为我的事件类型是错误的?我在网上搜索并尝试实施许多解决方案,但 none 到目前为止都有效。感谢任何帮助。
我的组件:
import React, { ChangeEvent, ChangeEventHandler, useState } from "react";
export default function Unidirectionflow() {
const [state4, setState4] = useState("");
const [state5, setState5] = useState("");
let handleChange4 = (e: React.FormEvent<HTMLInputElement>): void => {
setState3((e.target as HTMLInputElement).value);
};
let handleChange5 = (event: ChangeEvent<HTMLInputElement>) => {
setState5(event.currentTarget.value);
};
return (
<main>
<input type="text" value={state4} onChange={() => handleChange4} />
<input type="text" value={state5} onChange={() => handleChange5} />
</main>
);
}
https://react-typescript-cheatsheet.netlify.app/docs/basic/getting-started/forms_and_events/
您在调用函数时忘记传递event
试试这个
onChange={(e) => handleChange(e)}
或者
onChange={handleChange}
代码沙箱 => https://codesandbox.io/s/dreamy-pateu-1mc6j?file=/src/App.tsx
你可以这样做
export default function Unidirectionflow() {
const [states, setStates] = useState({
state3:'',
state4:''
})
const handleChange = (
e: React.ChangeEvent<HTMLTextAreaElement | HTMLInputElement>
) => {
setStates({
...states,
[e.target.name]: e.target.value.trim(),
});
};
return (
<main>
<input type="text" name="state3" value={states.state3} onChange={handleChange} />
<input type="text" name="state4" value={states.state4} onChange={handleChange} />
</main>
);
};
onChange={handleChange} 看看能不能帮到你!