为 keydown 添加事件侦听器以响应元素

xyi*_*ous 7 javascript reactjs

我正在尝试为keydown图像(或 div)标签中的事件添加事件侦听器。如果我使用 将它添加到文档中它会起作用document.addEventListener,但是当我尝试将它放入我在 react 创建的特定元素时它不会起作用(我在代码中指出了哪些有效,哪些无效)。也handleClick有效handleKey,但不管我用哪种格式将其放入标签中。

class PrescriptionImage extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      error: null,
      isLoaded: false,
      patient: "",
      rotation: 0
    };
    this.handleKey = this.handleKey.bind(this);
  }

  handleClick() {
    this.setState({rotation: this.state.rotation + 270})
  }

  handleKey(e) {
    e.preventDefault();
    console.log(e);
    if (e.code == 'ArrowLeft') {
      if (e.ctrlKey) {
        this.setState({rotation: this.state.rotation + 270})
      }
    }
  }

  componentDidMount() {
//    document.getElementById("left").addEventListener("keydown", this.handleKey, true); This doesn't work (no error)
//    this.RxImage.addEventListener("keydown", this.handleKey, false); This doesn't work, (can't find addEventListener of "undefined")
//    document.addEventListener("keydown", this.handleKey, false); This works.
    fetch("http://localhost:3333/patientAddress.json")
      .then(res => res.json())
      .then(
        result => {
          this.setState({
            isLoaded: true,
            patient: result.order.patient
          });
        },
        error => {
          this.setState({
            isLoaded: true,
            error
          });
        }
      );
  }

  componentWillUnmount(){
    document.removeEventListener("keydown", this.handleKey, false);
  }

  render() {
    const { error, isLoaded, patient, rotation } = this.state;
    if (error) {
      return <div>Error: {error.message}</div>;
    } else if (!isLoaded) {
      return <div>Loading...</div>;
    } else {
      return <img className="prescription-image" style={{width: "98%", height: "98%", transform: `rotate(${rotation}deg)`}} src={"data:image/png;base64," + patient.rx.imageData} onClick={() => this.handleClick()} onKeyDown={this.handleKey} />;
    }
  }
}

ReactDOM.render(<PrescriptionImage />, document.getElementById("left"));
Run Code Online (Sandbox Code Playgroud)

Sag*_*b.g 4

这里有两个主要问题:

  1. 事件keyDown需要div成为焦点。一种方法是tabindexdiv. 聚焦后,您可以onKeyDown在键盘上的任意键上触发该事件。
  2. 在您的处理程序中,您试图检查e.code但实际上正确的属性是e.keycode.
    话虽如此,您应该仔细阅读浏览器对它的支持,因为它在某些浏览器中被视为已弃用。
    以下是此事件的可用属性及其状态的列表key例如检查)。

编辑
我添加了另一种方法,使用react的ref API。通过这种方式,您可以按照之前的方式附加一个事件侦听器,并通过代码触发焦点(请参阅 参考资料componentDidMount)。

这是一个运行示例:

class App extends React.Component {

  componentDidMount() {
    this.myDiv.addEventListener('keydown', this.handleKey);
    this.myDiv.focus();
  }

  componentWillUnmount() {
    this.myDiv.removeEventListener('keydown', this.handleKey);
  }

  handleKey = e => {
    console.log(e.keyCode);
  }

  render() {
    return (
      <div>
        <div tabIndex="0" onKeyDown={this.handleKey}>click me</div>
        <div tabIndex="1" ref={ref => this.myDiv = ref}>by ref</div>
      </div>
    );
  }
}

ReactDOM.render(<App />, document.getElementById("root"));
Run Code Online (Sandbox Code Playgroud)
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="root"></div>
Run Code Online (Sandbox Code Playgroud)