我创建了一个从 Material UI 构建的
InputField
组件。当我试图将onKeyPress
传递给它时,它不起作用。当我将 InputField
更改为 input
时,代码有效。 onKeyPress
不是InputField
的道具。
输入组件:
<InputField
className={classes.InputContainer}
value={props.whatInput}
onChange={(e) => props.updateInputValue(e, "what")}
placeholder={"Job title, keywords or school"}
type="text"
onKeyPress={handleKeyPress}
/>
handleKeyPress
功能:
const handleKeyPress = (ev) => {
if (ev.key === "Enter") {
router.push({
pathname: "/teaching-jobs",
query: {
search_keywords: props.whatInput ? props.whatInput : "",
search_region: props.whereInput ? props.whereInput : "",
},
});
props.searchWhat();
ev.preventDefault();
}
};
技术栈:
TextField
组件:
<TextField
onKeyPress={(e) => {
if (e.key === "Enter") {
e.preventDefault();
handleEnter();
}
}}
/>
BTW -
type="text"
是 TextField
的默认值,所以它在这里是多余的。
可以这样用
onKeyPress= {(e) => {
console.log(' key pressed');
handleKeyPress(e)
}}
更多信息可以参考https://reactjs.org/docs/events.html#keyboard-events