为什么onKeyDown事件在React应用中不起作用?

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

onKeyDown功能组件中添加了React事件处理程序输入。按下虚拟iOS / mobil键盘上的DoneReturn时,应用程序需要重定向,但不会发生。为什么?实施有什么问题?

<input
  className={`${classes.borderedInput} ${classes.middleFont}`}
  placeholder={sm ? "events" : "city or place"}
  onFocus={deletePlaceholder}
  onBlur={e => makePlaceholder(e, sm ? "events" : "city or place")}
  onKeyDown={keyPress}
/>

const keyPress = e => {
  if (e.keyCode == 13) {
    this.props.history.push("/ongoingEventList");
  }
};

使用本教程来添加键盘监听器:

https://www.freecodecamp.org/forum/t/react-redux-adding-a-handler-for-enter-key-events/241151

reactjs keyboard virtual-keyboard
1个回答
0
投票

您正在使用functional组件,并且在keyPress处理程序中,您正在使用this

所以就做

props.history.push("/ongoingEventList");

完整示例

const KeyPressDemo = props => {
  const keyPress = e => {
    if (e.keyCode == 13) {
      props.history.push('/ongoingEventList')// remove `this`
    }
  };
  return (
    <input
      className={`${classes.borderedInput} ${classes.middleFont}`}
      placeholder={"city or place"}
      onFocus={deletePlaceholder}
      onBlur={e => makePlaceholder(e, sm ? "events" : "city or place")}
      onKeyDown={keyPress}
    />
  );
};

希望您在功能组件内部(而不是外部)定义keyPress处理程序,并正确使用history属性。

[如果仍然有问题,请发表评论。

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