(React/TypeScript) 将 onKeyDownEventHandler 添加到 canvas 元素中

(React/TypeScript) add onKeyDownEventHandler into a canvas element

我想在我的 canvas 元素中添加一个 onKeyDownEventHandler,但它并不顺利,redux 结构已正确设置并且我检查了 react-redux DevTool 代码没有执行操作.下面是我的代码:

reducers.ts

export const canvasReducer = (state:ICanvasState = initialState, action:ICanvasActions):ICanvasState=>{
switch(action.type){
    case "CHANGE_DIRECTION":
        return{
            ...state,
            direction:action.d
        }
    default:
        return state;
}
}

Canvas.tsx

handleKeyDown = (e:React.KeyboardEvent<Element>)=>{
if(e.keyCode === 37){
  this.props.changeDirection(Directions.LEFT)
}
if(e.keyCode === 38){
  this.props.changeDirection(Directions.UP)
}
if(e.keyCode === 39){
  this.props.changeDirection(Directions.RIGHT)
}
if(e.keyCode === 40){
  this.props.changeDirection(Directions.DOWN)
}
}
render() {
return (
  <canvas
  ref={this._canvasRef}
  width={26*25}
  height={26*25}
  onKeyDown={(e)=>this.handleKeyDown(e)}
  />
);

有人知道如何正确地将 onKeyDownEvent 实施到我的 canvas 中吗?谢谢

由于在您的情况下,React 正在尝试捕获 Canvas 元素的 keydown 事件。但是 Canvas 元素不是您可以关注的元素(更不用说在焦点上打字了)。

您可以尝试以下方法:

render() {
  return (
    <canvas
      ref={this._canvasRef}
      width={26*25}
      height={26*25}
      onKeyDown={(e)=>this.handleKeyDown(e)}
      tabIndex={0}
    />
  );
}

tabIndex 让您可以专注于 canvas。因为可以捕获 keydown 事件。希望这可以帮助。