reactjs 在 React 中使用 Link 组件时,如何修复 jsx-a11y/anchor-is-valid?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/47875730/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-06 04:18:56  来源:igfitidea点击:

How can I fix jsx-a11y/anchor-is-valid when using the Link component in React?

reactjseslintpa11y

提问by Eric the Red

In a React app

在 React 应用程序中

<Link to={`/person/${person.id}`}>Person Link</Link>

<Link to={`/person/${person.id}`}>Person Link</Link>

results in the following eslint error

导致以下 eslint 错误

The href attribute is required on an anchor. Provide a valid, navigable address as the href value jsx-a11y/anchor-is-valid

The href attribute is required on an anchor. Provide a valid, navigable address as the href value jsx-a11y/anchor-is-valid

The Link component results in a valid href attribute.

Link 组件产生一个有效的 href 属性。

<a href="#/person/2">Person Link</a>

<a href="#/person/2">Person Link</a>

What is the point of this error? How do I fix this?

这个错误有什么意义?我该如何解决?

Any help would be greatly appreciated!

任何帮助将不胜感激!

回答by Tomasz Mularczyk

The Linkcomponent generates hrefattribute so in the end anchor tag is valid from the accessibility point of view. Add an exceptionto .eslintrc:

Link组件生成href所以在端锚标签是从视点可访问有效属性。添加一个例外.eslintrc

{
  "rules": {
    "jsx-a11y/anchor-is-valid": [ "error", {
      "components": [ "Link" ],
      "specialLink": [ "to" ]
    }]
  }
}

Additionally, there is the same issue with a answer on GitHub.

此外,GitHub 上的答案也存在同样的问题。

回答by Roni Chabra

you can just write some text content inside the "a" tag and hide it with CSS (font-size:0px or something

你可以在 "a" 标签内写一些文本内容并用 CSS (font-size:0px 或其他东西) 隐藏它

回答by turonno

Perhaps you meant to put backticks instead of single-quotes in order to create a template literal. Try the following:

也许您打算用反引号代替单引号来创建模板文字。请尝试以下操作:

<Link to={`/person/${this.state.id}/edit`}>Edit</Link>