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

问题描述 投票:0回答:2

我创建了一个从 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();
  }
};

技术栈:

  1. “下一步”:“^9.5.1”,
  2. “反应”:“^ 17.0.2”,
  3. "@material-ui/core": "^4.11.0",
  4. "@material-ui/icons": "^4.9.1",
  5. "@material-ui/lab": "^4.0.0-alpha.56",
  6. "@material-ui/pickers": "^3.2.10",
  7. "@mui/icons-material": "^5.3.1",
  8. "@mui/material": "^5.3.1",
  9. "@mui/x-data-grid": "^5.5.0",
reactjs next.js react-props onkeypress
2个回答
0
投票

使用

TextField
组件:

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

BTW -

type="text"
TextField
的默认值,所以它在这里是多余的。


-1
投票

可以这样用

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

更多信息可以参考https://reactjs.org/docs/events.html#keyboard-events

© www.soinside.com 2019 - 2024. All rights reserved.