next.js 如何将onKeyPress添加到自定义React组件?

sf6xfgos  于 2023-04-30  发布在  React
关注(0)|答案(2)|浏览(121)

我已经创建了一个从Material UI构建的InputField组件。当我试图传递onKeyPress给它时,它不起作用。当我将InputField更改为input时,代码可以正常工作。onKeyPress不是InputField的 prop 。

输入组件:

<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();
  }
};

技术栈:

1.“next”:“^9.5.1英寸,
1.“react”:“^17.0.2”,
1.“@material-ui/core”:“^4.11.0”,
1.“@material-ui/icons”:“^4.9.1”
1.“@material-ui/lab”:“^ www.example.com ”,
1.“@material-ui/pickers”:“^3.2.10”,
1.“@mui/icons-material”:“^5.3.1”,
1.“@mui/material”:“^5.3.1”,
1.“@mui/x-data-grid”:“^5.5.0”,

owfi6suc

owfi6suc1#

使用TextField组件:

<TextField
  onKeyPress={(e) => {
    if (e.key === "Enter") {
      e.preventDefault();
      handleEnter();
    }
  }}
/>

顺便说一句-type="text"TextField的默认值,所以在这里是多余的。

aoyhnmkz

aoyhnmkz2#

你可以这样用

onKeyPress= {(e) => {
              console.log(' key pressed');
              handleKeyPress(e)    
    }}

有关更多信息,请参阅 www.example.com

相关问题