繁体   English   中英

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

[英]adding event listener for keydown to react element

我正在尝试在图像(或div)标签中为keydown事件添加事件侦听器。 如果我使用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"));

您在这里遇到2个主要问题:

  1. keyDown事件需要div成为焦点。 一种方法是在div添加一个tabindex属性。 专注onKeyDown之后,您可以在键盘上的任何键上触发onKeyDown事件。
  2. 在处理程序中,您尝试检查e.code但实际上正确的属性是e.keycode
    如此说来,您应该仔细阅读浏览器对其的支持,因为某些浏览器认为它已弃用。
    这是此事件的可用属性及其状态的列表 (例如,选中key )。

编辑
我使用reactref 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")); 
 <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> 

此实现对我来说效果很好。

class App extends React.Component {

  constructor(props) {
    super(props);
    this.myDiv = React.createRef();
  }

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

  componentWillUnmount() {
    this.myDiv.current.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={this.myDiv}>by ref</div>
      </div>
    );
  }
}

ReactDOM.render(<App />, document.getElementById("root"));

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM