如何在我的onClick处理程序中添加键盘侦听器? [英] How to add a keyboard listener to my onClick handler?

查看:983
本文介绍了如何在我的onClick处理程序中添加键盘侦听器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下内容:

class MyTextArea extends React.Component {

  handleClick = () => {
    this.focus();
  }

  focus = () => this.ref.focus;

  handleRef = (component) => {
    this.ref = component;
  };

  render() {
    return (
      <div className="magicHelper" onClick={this.handleClick}>
        <textarea></textarea>
      </div>
    );
  }
}

我的CSS:

.magicHelper {
  width: 100%;
  height: 100%;
}
textarea {
  line-height: 32px;
}

我需要这个,因为我需要将textarea的占位符水平和垂直居中在页面中。给定文本区域不能使文本垂直居中,我需要使文本区域的高度保持较短。因此,我需要这样做,以便当用户在文本区域之外单击时,以为他们在单击文本区域时,文本区域会自动聚焦在该区域中。

I need this because I need the textarea's placeholder are to be horizontally and vertically centered in the page. Given textareas can't vertically center text, I need to keep the height of the textarea short. I therefore need to make it so when the user clicks outside of the textarea, thinking they are clicking the the textarea, the textarea auto focuses in.

这会导致ESLint错误:具有单击处理程序的可见,非交互式元素必须至少具有一个键盘侦听器。

This is causing an ESLint error: "Visible, non-interactive elements with click handlers must have at least one keyboard listener". How can I update the above to pass eslint?

推荐答案

https://github.com/evcohen/eslint-plugin-jsx- a11y / blob / master / docs / rules / click-events-have-key-events.md

似乎此规则是为了强制执行辅助功能标准。

It seems this rule is to enforce Accessibility standards.

基于此,更改代码以执行类似的操作

Based on this, change your code to do something like this

<div className="magicHelper" onClick={this.handleClick} onKeyDown={this.handleClick}>

您也可以在eslint中禁用该规则,我想这取决于偏好。

You could also disable the rule in eslint, I suppose it depends on preference.

这篇关于如何在我的onClick处理程序中添加键盘侦听器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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