【问题标题】:React keydown event capturing and bubblingReact keydown 事件捕获和冒泡
【发布时间】:2018-05-22 19:13:33
【问题描述】:

我想从孩子那里捕捉 keydown 事件。这可能吗? 所以说我有

onKeyDown = e => {
 e.stopPropagation();
 console.log("Hello world from Parent!");
 return false;
}

<ParentComponent onKeyDown={this.onKeyDown}>
  <div tabIndex='0' id='child'>Focus on me and press a button!</div>
</ParentComponent>

当您在关注 div 子项时按下按钮时,我想打印“Hello World”。

我已经尝试过了,但似乎不起作用,并且阅读另一个SO thread,只要使用e.stopPropagation(),它似乎就可以与点击处理程序一起使用。为什么它不适用于 keydown 事件?

【问题讨论】:

    标签: reactjs events


    【解决方案1】:

    我猜你实际上并没有使用 ParentComponent 中传递的 onKeyDown 属性。您需要像这样使用它:

    class ParentComponent extends Component {
      render(){
        return(
          <div onKeyDown={this.props.onKeyDown}>
            {this.props.children}
          </div>
        )
      }
    };
    

    See this working example

    根据 OP 在下面 cmets 中的问题...

    无状态:

    const ParentComponent = (props) => (
      <div onKeyDown={props.onKeyDown}>{props.children}</div>
    )
    

    在 div 中:

    const ParentComponent = (props) => (
      <div>
        <div onKeyDown={props.onKeyDown}>{props.children}</div>
      </div>
    )
    

    【讨论】:

    • 如果
      内怎么办?
    • 如果子组件是无状态的呢?
    • @Pants 看看我上面添加的内容
    猜你喜欢
    相关资源
    最近更新 更多
    热门标签