为什么 onKeyDown 事件在 React 应用程序中不起作用?
Why onKeyDown event has no effect in React app?
在 React
功能组件中添加了 onKeyDown
事件处理程序输入。当按下虚拟 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
道具。
如果还有问题,请发表评论..
在 React
功能组件中添加了 onKeyDown
事件处理程序输入。当按下虚拟 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
道具。
如果还有问题,请发表评论..