关于reactjs:onKeyDown事件不适用于React中的div

onKeyDown event not working on divs in React

我想在React中的div上使用keyDown事件。 我做:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
  componentWillMount() {
      document.addEventListener("keydown", this.onKeyPressed.bind(this));
  }

  componentWillUnmount() {
      document.removeEventListener("keydown", this.onKeyPressed.bind(this));
  }      

  onKeyPressed(e) {
    console.log(e.keyCode);
  }

  render() {
    let player = this.props.boards.dungeons[this.props.boards.currentBoard].player;
    return (
      <div
        className="player"
        style={{ position:"absolute" }}
        onKeyDown={this.onKeyPressed} // not working
      >
       
         
            <img src={IMG_URL+player.img} />
         
       
     
    )
  }

它工作正常,但我想以React风格做更多。 我试过了

1
        onKeyDown={this.onKeyPressed}

在组件上。 但是它没有反应。 我记得它可以处理输入元素。

码笔

我该怎么做?


您应该使用tabIndex属性,以便能够在React中的div上监听onKeyDown事件。设置tabIndex =" 0"应该会触发您的处理程序。


你需要这样写

1
2
3
4
5
6
<div
    className="player"
    style={{ position:"absolute" }}
    onKeyDown={this.onKeyPressed}
    tabIndex="0"
  >

如果onKeyPressed未绑定到this,则尝试使用箭头函数重写它或将其绑定在组件constructor中。


您在纯Javascript中考虑过多。摆脱那些React生命周期方法上的侦听器,并使用event.key而不是event.keyCode(因为这不是JS事件对象,所以是React SyntheticEvent)。您的整个组件可能就这么简单(假设您尚未在构造函数中绑定方法)。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
onKeyPressed(e) {
  console.log(e.key);
}

render() {
  let player = this.props.boards.dungeons[this.props.boards.currentBoard].player;
  return (
    <div
      className="player"
      style={{ position:"absolute" }}
      onKeyDown={(e) => this.onKeyPressed(e)}
    >
     
       
          <img src={IMG_URL+player.img} />
       
     
   
  )
}


答案与

1
2
3
4
5
<div
    className="player"
    onKeyDown={this.onKeyPressed}
    tabIndex={0}
>

对我有用,请注意,tabIndex需要一个数字,而不是字符串,因此tabIndex =" 0"不起作用。


您在构造函数中缺少方法的绑定。这就是React建议您这样做的方式:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Whatever {
  constructor() {
    super();
    this.onKeyPressed = this.onKeyPressed.bind(this);
  }

  onKeyPressed(e) {
    // your code ...
  }

  render() {
    return ();
  }
}

还有其他方法可以执行此操作,但这将是运行时最有效的方法。


您必须防止触发默认事件。

1
2
3
4
onKeyPressed(e) {
   e.preventDefault();
   console.log(e.key);
}