反应不响应按键事件 [英] React not responding to key down event

查看:44
本文介绍了反应不响应按键事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试实现一些非常基本的按键检测,但我根本无法让它工作.我有一个应该在 onKeyDown 事件上接收的裸组件,但控制台中没有任何内容被注销:

class App 扩展 React.Component {构造函数(道具){超级(道具);}handleKeyDown(事件){console.log('处理按键');}使成为() {返回 (<ChildComponent onKeyDown={this.handleKeyDown}/>);}}React.render(, document.getElementById('app'));

解决方案

问题在于 ChildComponent 不是组件而是组件工厂.它将替换为渲染该工厂创建的元素的结果.

在 div 中插入 ChildComponent 并将任何事件侦听器附加到 div,而不是 ChildComponent.如果需要内联显示,请将

替换为 .

let {Component} = React;类 ChildComponent 扩展组件 {使成为() {return ( <child-component>按下一个键</child-component>);}}类 App 扩展组件 {handleKeyDown(事件){console.log('处理按键');}使成为() {return ( <div onKeyDown={this.handleKeyDown}><ChildComponent/></div> );}}React.render(, document.getElementById('app'));

codepen

上查看它的实际效果

I'm trying to implement some very basic key press detection and I can't get it to work at all. I have a bare component that should be picking up on the onKeyDown event but nothing gets logged out in the console:

class App extends React.Component {
  constructor(props) {
    super(props);
  }

  handleKeyDown(event) {
    console.log('handling a key press');
  }

  render() {
    return (
      <ChildComponent onKeyDown={this.handleKeyDown} />
    );
  }
}

React.render(<App />, document.getElementById('app'));

解决方案

The problem is that ChildComponent is not a component but a component factory. It will be replaced with the result of rendering the element created with that factory.

Insert the ChildComponent in a div and attach any event listener to the div, not ChildComponent. Replace <div> with <span> if you need inline display.

let {Component} = React;

class ChildComponent extends Component {
  render() {
    return ( <child-component>press down a key</child-component> );
  }
}

class App extends Component {
  handleKeyDown(event) {
    console.log('handling a key press');
  }

  render() {
    return ( <div onKeyDown={this.handleKeyDown}><ChildComponent  /></div> );
  }
}

React.render(<App />, document.getElementById('app'));

See it in action on codepen

这篇关于反应不响应按键事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆