首页 > 解决方案 > 将 `eslint-plugin-jsx-a11y` 与 `styled-components` 一起使用

问题描述

该库styled-components使您能够创建自定义样式的组件,例如:

const Button = styled.div`
  display: inline-block;
  border-radius: 3px;
  padding: 0.5rem 0;
  margin: 0.5rem 1rem;
  width: 11rem;
  background: transparent;
  color: white;
  border: 2px solid white;
`;

function App(props) {
  return (<Button onClick={() => console.log("clicked!")}>Styled</Button>);
}

以下按钮是可点击的,但由<div />元素组成,因此eslint-plugin-jsx-a11y通常需要tabIndex,role等属性。

问题是因为从styled.divES-Lint 创建的组件看不到它。这个问题有插件或解决方案吗?

标签: reactjsaccessibilityeslintstyled-components

解决方案


我为此制作了一个非常酷的插件(希望如此)。它在我的一个存储库中发现了 6,567 个错误,这些错误是使用 airbnb/jsx-a11y 规则未发现的。请给它一颗星,这样我们就可以让更多人感兴趣,使用它,并为让所有人都能访问互联网做出贡献。

这是github 存储库,它涵盖了所有 4 种风格的组件/情感语法

现有的 a11y linting 已经变得不那么有用了(就我个人而言,我需要 linting 的 99% 的组件都是样式化的。)。下面的每个场景都会显示错误

Visible, non-interactive elements with click handlers must have at least one keyboard listener.`
const Div = styled.div``;
<Div onClick={() => null}/>
const Div = styled.div.attrs({ onClick: () => null})``;
<Div />
const Div = styled.div.attrs({ onClick: () => null})``;
const StyledDiv = styled(Div)``;
<StyledDiv />
const ButtonAsDiv = styled.button``;
<ButtonAsDiv as="div" onClick={() => null} />

它并不完美(没有 linters),但它非常有用,加上一点时间和社区支持,它可能会更好。


推荐阅读