在我的项目中,我们有以下代码行:
<span
onClick={this.toggleEditing}
>
{this.state.value}
</span>
不用说,它会在 eslint 中产生错误,并显示消息"可见的非交互式元素不应具有鼠标或键盘事件侦听器 jsx-a11y/no-static-element-interactions"。但我不知道解决这种情况的最佳方法是什么,我们是否应该将其更改为按钮并将样式更改为看起来像跨度。我对这个问题真的没有太多经验。
看看文档,它很漂亮地告诉你该怎么做 https://github.com/evcohen/eslint-plugin-jsx-a11y/blob/master/docs/rules/no-static-element-interactions.md#how-do-i-resolve-this-error
对于您的情况,解决方案是添加role="button"
<span onClick={this.toggleEditing} role="button">
{this.state.value}
</span>
我用这个修复了它:
<span
role="button"
tabIndex={0}
title="Some title"
onClick={this.toggleEditing}
onKeyPress={this.toggleEditing}
>
{this.state.value}
</span>
错误是什么? onClick 转换为 DOM 中有效的事件(单击跨度),因此您应该能够完成这项工作。