1

I want to add a onKeyDownEventHandler into my canvas element, but it didn't go well, the redux structure has been correctly set and I checked react-redux DevTool the code doesn't execute the action. Below is my code:

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)}
  />
);

Anyone have clue how to implement the onKeyDownEvent into my canvas correctly? thanks

Yin
  • 13
  • 3

1 Answers1

2

Since in your case , React is trying to capture the keydown event of the Canvas element. But Canvas element is not an element that you can focus on(let alone typing with it on focus).

You can try the following:

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

The tabIndex allows you to focus on the canvas. Since making it possible to capture the keydown event. Hope this helps.