【问题标题】:(React/TypeScript) add onKeyDownEventHandler into a canvas element(React/TypeScript) 将 onKeyDownEventHandler 添加到画布元素中
【发布时间】:2020-07-03 13:05:00
【问题描述】:

我想在我的画布元素中添加一个 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 实现到我的画布中吗?谢谢

【问题讨论】:

    标签: reactjs react-redux react-tsx


    【解决方案1】:

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

    您可以尝试以下方法:

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

    tabIndex 允许您专注于画布。由于可以捕获 keydown 事件。希望这可以帮助。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-03-12
      • 1970-01-01
      • 1970-01-01
      • 2022-01-06
      • 2018-06-01
      • 2016-08-28
      相关资源
      最近更新 更多