我在 React 中处理输入的方式有什么问题?我想检测键码并防止将它们输入到输入中,但现在下面的代码似乎不起作用。
const Input = ({ placeholder }) => { const [inputValue, setInputValue] = useState("");
const handleKeyDown = e => {
console.log(e.target.value);
if ([188].includes(e.keyCode)) {
console.log("comma");
} else {
setInputValue(e.target.value);
} };
return (
<div>
<input
type="text"
value={inputValue}
onKeyDown={handleKeyDown}
placeholder={placeholder}
/>
</div> ); };
https://codesandbox.io/s/ancient-waterfall-43not?file=/src/App.js
最佳答案
您需要调用e.preventDefault()
,但您还需要将onChange 处理程序添加到输入:
const handleKeyDown = e => {
console.log(e.key);
if ([188].includes(e.keyCode)) {
console.log("comma");
e.preventDefault();
}
};
const handleChange = e => setInputValue(e.target.value);
...
<input
type="text"
value={inputValue}
onChange={handleChange}
onKeyDown={handleKeyDown}
placeholder={placeholder}
/>
关于javascript - onKeyDown 从 e.target.value 获取值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62125195/