reactjs - 为什么 onKeyDown 事件在 React 应用程序中不起作用?
问题描述
在功能组件中添加onKeyDown
了事件处理程序输入。React
应用程序需要在按下虚拟 iOS / mobil 键盘时Done
或Return
上进行重定向,但不会发生。为什么?实施有什么问题?
<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
解决方案
您正在使用一个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
正确使用道具。
如果还有问题,请发表评论..
推荐阅读
- javascript - 从 json 字符串中获取匹配范围键的值
- java - SQL插入查询从文件url中删除字符
- python - GPT-2 语言模型:将解码器-转换器输出与令牌嵌入或另一个权重矩阵相乘
- ios - 带有谷歌地图 API 路线的 Json 文件
- neo4j - 从一个节点到另一个节点的多个关系
- javascript - Swiper 滑块在视口中的幻灯片上的活动类和当前类仅在一个上
- jquery - 如何使用延迟对象从一个 api 调用获取数据到另一个?
- go - 这个示例客户端的 Go GRPC 服务器应该如何?
- oauth-2.0 - Google 操作和 Auth0 帐户关联令牌每 24 小时过期一次
- python - readthedocs 上的 nbsphinx 语法高亮显示