创建react应用程序_掌握您的React应用程序的可访问性

本文探讨了如何遵循Web内容可访问性指南(WCAG)来创建无障碍的React应用,介绍了ARIA属性的重要性,并推荐了几个测试框架,如eslint-plugin-jsx-a11y、React Axe和cypress-axe,以确保在开发过程中检测和修复可访问性问题。同时,强调了对比度、键盘导航和兼容性等关键因素,以实现全面的无障碍体验。
摘要由CSDN通过智能技术生成

创建react应用程序

On WCAG guidelines, ARIA attributes, and testing frameworks.

关于WCAG准则,ARIA属性和测试框架。

Accessibility across web apps is key to ensure the inclusion of those living with disabilities. According to the WHO, around 15% of the global population lives with some form of disability, with at least 2.2 billion people having a visual impairment. The International Classification of Functioning, Disability and Health (ICF) defines disability as an umbrella term for impairments, activity limitations, and participation restrictions. That’s a considerable amount of the population struggling to smoothly navigate through a website. Even with today’s built-in smartphone accessibility features, there are things we can do as developers to ensure all bases are covered.

跨Web应用程序的可访问性是确保将残障人士包括在内的关键。 根据世界卫生组织的数据,全球约有15%的人患有某种形式的残疾,至少有22亿人有视力障碍。 国际功能,残疾与健康分类(ICF)将残疾定义为损害,活动限制和参与限制的总称。 那是相当数量的人们在努力顺利浏览网站。 即使具有当今内置的智能手机可访问性功能,开发人员也可以做一些事情来确保覆盖所有基础。

I recently watched React Geekle’s online React Global Summit where the topic of accessibility was touched upon a couple of times. After learning some very useful tools and concepts, I thought I’d write about some of them here for developers who may also want to contribute towards accessibility excellence.

最近,我观看了React Geekle的在线React全球峰会,其中几次涉及到可访问性话题。 在学习了一些非常有用的工具和概念之后,我想在这里为那些可能还想为卓越的可访问性做出贡献的开发人员撰写其中的一些文章。

Web内容可访问性指南(WCAG) (Web Content Accessibility Guidelines (WCAG))

WCAG — developed by a W3C initiative called The Web Accessibility Initiative (WAI) — provides developers with technical specifications and guidelines on how to increase web usability for people with disabilities. The latest WCAG version is 2.1 with 2.2 scheduled to be released in early 2021. A working draft of version 2.2 can be seen here.

WCAG是由W3C倡议(称为Web无障碍倡议(WAI))开发的,旨在为开发人员提供有关如何提高残疾人的Web可用性的技术规范和指南。 WCAG的最新版本是2.1,计划于2021年初发布。2.2的工作草案可以在此处查看

There are 4 main principles to the WCAG:

WCAG有4条主要原则

Perceivable — all user interface components must be presented to users in a way they can receive it i.e. it can’t be invisible to all of their senses.

可感知的—所有用户界面组件都必须以一种可以接收的方式呈现给用户,即,所有感官都不能被看不见。

Operable — users must be able to operate the interface.

可操作-用户必须能够操作该界面。

Understandable — the user must understand how to use the interface. Functionalities must not be beyond their understanding.

可以理解-用户必须了解如何使用该界面。 功能一定不能超出他们的理解范围。

Robust — it must be robust enough that if technologies advance, the content must still be accessible by users.

健壮—它必须足够健壮,以至于技术进步时,用户仍必须可以访问内容。

According to WCAG, if any of the above isn’t true, users with disabilities will not be able to access the web.

根据WCAG的说法,如果以上任何一项都不成立,那么残疾用户将无法访问网络。

Each of the above principles will have sub-guidelines which in turn have success criteria. Below I’ve listed a few of the guidelines found within each principle. A full list can be found on WCAG’s website.

以上每个原则都有子指南,而子指南又有成功标准。 下面,我列出了每个原则中的一些准则。 完整列表可以在WCAG的网站上找到。

可感知的准则 (Perceivable Guidelines)

  • Text Alternative — e.g. alt text in images. Any content that isn’t text should have a text alternative.

    替代文字-例如图像中的alt文字。 任何非文本的内容都应具有替代文本。

  • Distinguishable — separating foreground and background colour to make content easy to read.

    可区分—区分前景色和背景色以使内容易于阅读。

可操作准则 (Operable Guidelines)

  • Keyboard Accessible — make all functionality available from the keyboard.

    键盘可访问-使键盘上的所有功能可用。

  • Navigable — provide ways for users to navigate, find content, and determine where they are.

    可导航-为用户提供导航,查找内容并确定其位置的方式。

可以理解的准则 (Understandable Guidelines)

  • Readable — make the content readable and understandable.

    可读-使内容可读和可理解。

  • Input Assistance — help users avoid and correct mistakes.

    输入协助-帮助用户避免和纠正错误。

稳健的准则 (Robust Guidelines)

  • Compatible — maximise compatibility with current or future user agents.

    兼容-最大化与当前或将来的用户代理的兼容性。

Each guideline will have testable success criteria based on three levels of conformance A (lowest), AA, and AAA (highest).

每条准则将基于A (最低), AAAAA (最高)三个级别的可测试成功标准。

Check out the complete list on their website to find detailed success criteria.

在他们的网站上查看完整列表,以找到详细的成功标准。

对比度 (Contrast Ratios)

I mentioned earlier that there are 3 levels of success criteria (A, AA, AAA) for the WCAG principle guidelines. To my surprise, contrast ratio checking is built into Google Chrome allowing you to check your site’s contrast ratio rating. Open up devtools and inspect an element with a background colour or colour, then click on the tiny coloured square in front of the HEX code. In the example below, I took a fresh copy of a create-react-app app and inspected the ‘Learn React’ link:

我之前提到过,WCAG原则准则有3个成功标准级别(A,AA,AAA) 。 令我惊讶的是,Google Chrome浏览器内置了对比度检查功能,可让您检查网站的对比度等级。 打开devtools并检查具有背景色或颜色的元素,然后单击十六进制代码前面的小方块。 在以下示例中,我制作了一个create-react-app应用程序的新副本,并检查了“ Learn React”链接:

Image for post

As you can see it scores pretty high with a rating of AA and above. However, WCAG warns that even content with the highest rating of AAA will not necessarily be accessible by all.

如您所见,它在AA或以上等级中的得分很高。 但是,WCAG警告说,即使是具有AAA最高评级的内容也不一定所有人都可以访问。

Another handy tool I was made aware of if you prefer checking your contrast ratio in a separate environment is Contrast Ratio. By entering your background colour on the left and text colour on the right, the site will generate a rating for you.

如果您更愿意在单独的环境中检查对比度,我就知道了另一个方便的工具,就是对比度。 通过在左侧输入背景色和在右侧输入文本色,站点将为您生成一个评级。

辅助功能丰富的Internet应用程序(ARIA) (Accessibility Rich Internet Applications (ARIA))

Most developers will have either used or come across aria attributes at some point in their career.

大多数开发人员在其职业生涯的某个时候会使用或遇到过aria属性。

Accessible Rich Internet Applications (ARIA) is a set of attributes that define ways to make web content and web applications (especially those developed with JavaScript) more accessible to people with disabilities — MDN

可访问的富Internet应用程序(ARIA)是一组属性,这些属性定义了使残障人士更易于访问Web内容和Web应用程序(尤其是使用JavaScript开发的那些内容)的方法-MDN

Initially introduced in 2008, it wasn’t until 2014 when it became a W3C recommendation.

最初于2008年推出,直到2014年成为W3C建议。

Adding aria attributes can provide tremendous benefits when coupled with screen readers. Using ChromeVox on my Mac, I was able to get voice-overs for those elements with aria attributes. In situations where only a certain input format is accepted or there are errors, these are extremely useful.

屏幕阅读器结合使用时,添加aria属性可以带来巨大的好处。 在Mac上使用ChromeVox ,我能够为具有aria属性的那些元素提供画外音。 在仅接受某种输入格式或存在错误的情况下,这些功能非常有用。

<div>
  <label htmlFor="date">Date</label>
  <input name="date" id="date" aria-describedby="date-info" />
  <span id="date-info">must be in dd/mm/yy format</span>
</div>

The role attribute is also one worth mentioning here. The alert role is used to communicate an important and usually time-sensitive message to the user. Again with a screen reader, the error is immediately read out to the user.

这里的role属性也是值得一提的。 警报角色用于向用户传达重要且通常对时间敏感的消息。 再次使用屏幕阅读器,错误立即被读出给用户。

<div role="alert">Uhoh, an error occurred!</div>

CSS陷阱(CSS Gotchas)

弹性盒(Flexbox)

I use flexbox in all my projects but it hadn’t occurred to me before that the nature of its functionality may cause accessibility issues. Because you can reorder elements using flexbox, if you were to tab through say a grid of items positioned with flexbox, the next highlighted item would be unknown. If using the order CSS property, at times the user may tab from the top of the page to the bottom and back up again. Items in the wrong order also affect screen readers as they read directly from the DOM. Whilst it’s easy to make quick fixes with CSS, it’s best to get to the root of the problem. The advice for this is to ensure the source code is kept in alignment with the design.

我在所有项目中都使用了flexbox ,但是在它的功能性质可能导致可访问性问题之前,我从未想到过。 因为您可以使用flexbox来对元素进行重新排序,所以如果要通过标签说出使用flexbox定位的项目网格,则下一个突出显示的项目将是未知的。 如果使用order CSS属性,则用户有时可能会从页面顶部到底部进行制表,然后再次备份。 错误顺序的项目也会影响屏幕阅读器,因为它们直接从DOM中读取。 尽管使用CSS进行快速修复很容易,但是最好是找出问题的根源。 这样做的建议是确保源代码与设计保持一致。

显示 (Display)

Styles like display: none or visibility: hidden are no-no’s as they hide elements from screen readers. Instead, style it in a way so that it won’t show. An example of this could include setting all borders and padding, as well as the width and the height, of the element to 0 .

display: none这样的样式display: nonevisibility: hidden是不对,因为它们会隐藏屏幕阅读器中的元素。 而是以某种方式设置样式,使其不会显示。 这样的一个示例可能包括将元素的所有边框和填充以及宽度和高度设置为0

禁用按钮 (Disabled Button)

In the summit, it was considered bad practice to set the disabled attribute on a button as this removes it from the accessibility tree. Instead, style as greyed out to appear as disabled, and add pointer-events: none which will prevent any actions from taking place if clicked on. For the non-sighted user, you may also use the aria-disabled attribute.

在峰会上,在按钮上设置disabled属性被认为是不好的做法,因为这会将其从辅助功能树中删除。 取而代之的是,将样式设置为灰色以显示为已禁用,并添加pointer-events: none如果不单击,则不会阻止任何动作。 对于没有视力的用户,您也可以使用aria-disabled属性。

Eslint-插件-jsx-a11y (Eslint-plugin-jsx-a11y)

The eslint-plugin-jsx-a11y package is a static checker for accessibility rules on jsx elements.

eslint-plugin-jsx-a11y软件包是用于jsx元素上可访问性规则的静态检查器。

After installing as per the Github repo, it should be added to a plugins array within your package.json

按照Github存储库安装后,应将其添加到package.json的plugins数组中package.json

"plugins": ["jsx-a11y"],

Next, add a script entry to the scripts object on the same file:

接下来,将脚本条目添加到同一文件上的scripts对象中:

"lint": "eslint src"

Running npm run lint will generate an output on your command prompt with any accessibility violations.

运行npm run lint会在命令提示符下生成任何可访问性违规的输出。

Image for post

Most IDEs will come with eslint support out of the box and so violations like the image one above will automatically highlight for you prior to installing any lint packages.

大多数IDE都具有开箱即用的eslint支持,因此在安装任何lint软件包之前,如上图所示的违规行为会自动为您突出显示。

Image for post

React斧 (React Axe)

This very useful tool will log out accessibility violations and their severities to the console! Grab the package from here and once installed, make sure it’s only running on development mode as it can have an impact on performance in production.

这个非常有用的工具会将可访问性违规及其严重性注销到控制台! 从这里获取软件包,并在安装后确保其仅在开发模式下运行,因为这可能会对生产性能产生影响。

if (process.env.NODE_ENV !== 'production') {
var axe = require('react-axe');
axe(React, ReactDOM, 1000);
}

That’s all the setup you need to do to view any violations.

这就是查看任何违规所需的全部设置。

Image for post

测验 (Testing)

All of the above are excellent ways to stay on top of accessibility rule violations within your React web app. There really is no excuse to not make our sites as accessible as possible. We can take it one step further, however, with tests!

以上所有都是在React Web应用程序中掌握可访问性规则冲突的绝佳方法。 确实没有任何借口不使我们的网站尽可能地不被访问。 但是,通过测试,我们可以更进一步!

开玩笑的斧头 (Jest Axe)

Jest Axe is a plugin for Jest using the axe-core rules engine, the same engine rules used in React Axe mentioned earlier.

Jest Ax是使用轴核心规则引擎的Jest插件,与先前提到的React Ax中使用的引擎规则相同。

Head over to the Github repo and install the package. Note if you’re not already using Jest in your application, you will need to install that first.

前往Github仓库并安装软件包。 请注意,如果您尚未在应用程序中使用Jest ,则需要先安装它。

npm install --save-dev jestnpm install --save-dev jest-axe

Once installed, writing tests is quite simple:

安装后,编写测试非常简单:

import { render } from '@testing-library/react';
import App from './App';
import { axe, toHaveNoViolations } from 'jest-axe';
import { Form } from './Form';


expect.extend(toHaveNoViolations);


it('should not violate accessibility rules', async () => {
  const Form = document.createElement('div');
  ReactDOM.render((
    <Form />
  ), Form);


  const results = await axe(Form);


  expect(results).toHaveNoViolations();
})

We’re creating a div and rendering a component of our choice inside it. We then pass the div containing our component to axe and make use of the toHaveNoViolations() matcher that jest-axe provides us with.

我们正在创建一个div,并在其中渲染我们选择的组件。 然后,我们将包含组件的div传递给ax,并利用jest-axe提供给我们的toHaveNoViolations()匹配器。

Run your test file as you normally would via your package.json command (usually npm test ) to get your results.

像通常一样通过package.json命令(通常为npm test )运行测试文件以获取结果。

Image for post

You can see this produces similar results to previous approaches where our image element is missing an alt attribute.

您可以看到,这会产生与以前的方法类似的结果,在以前的方法中,我们的图像元素缺少alt属性。

axe-webdriverjs (axe-webdriverjs)

Selenium Web Driver is an excellent example of end-to-end testing. With the user of linters, React Axe and Jest Axe, the checking of violations is a very manual process. End-to-end testing automates the auditing of our components making our lives much easier should we have multiple test files.

Selenium Web驱动程序是端到端测试的一个很好的例子。 对于使用linters,React Ax和Jest Axe的用户,违规检查是一个非常手动的过程。 端到端测试使我们的组件审计自动化,从而在我们拥有多个测试文件的情况下使我们的生活变得更加轻松。

axe-webdriverjs provides a chainable API to use with Selenium’s WebDriverJS, once again using the axe-core engine.

axe-webdriverjs提供了一个可链接的API,可Selenium的WebDriverJS一起使用,再次使用axe-core引擎。

Run the below commands to install both packages.

运行以下命令以安装两个软件包。

npm install selenium-webdrivernpm install axe-webdriverjs --save

After installing, the set up is quite simple with only a few lines of code needed to get it up and running.

安装后,设置非常简单,只需几行代码即可启动并运行。

const WebDriver = require('selenium-webdriver');
const AxeBuilder = require('axe-webdriverjs');


const driver = new WebDriver.Builder()
    .forBrowser('chrome')
    .build();


driver
    .get('localhost:3001')
    .then(() => {
        AxeBuilder(driver).analyze((err, results) => {
            if (err) {
                // handle error
            }
            console.log(results);
        });
    });

Make sure you adjust the port to reflect the one you’re running your React site on.

确保调整端口以反映正在运行React网站的端口。

Run node end-to-end-testing.js replacing the file name with yours, and you should see an additional Chrome window open up immediately. Your test results will also appear immediately in your command prompt in the form of an object.

运行node end-to-end-testing.js并将文件名替换为您的文件名,您应该会立即看到另一个Chrome窗口打开。 测试结果还将立即以对象的形式出现在命令提示符中。

Image for post

A number of passes will appear with those elements complying with accessibility rules. Likewise, you will also see an array of violations that need looking into.

符合可访问性规则的那些元素将出现许多通过。 同样,您还将看到需要调查的一系列违规情况。

Image for post

柏树轴 (cypress-axe)

Cypress is another well known end-to-end JavaScript testing framework boasting a nicer UI than Selenium Web Driver to display test results. If you’re already using cypress, this will be a breeze. If you’re new to Cypress, it will also be a breeze as it’s extremely easy to set up and get it up and running.

赛普拉斯是另一个众所周知的端到端JavaScript测试框架,它拥有比Selenium Web Driver更好的UI来显示测试结果。 如果您已经在使用赛普拉斯,那将是一件轻而易举的事情。 如果您不熟悉赛普拉斯,那也将是一件轻而易举的事,因为它非常容易设置和运行。

cypress-axe is a plugin for Cypress providing us with checkA11y() for all of our accessibility testing. Once again this uses the axe-core plugin.

cypress-axe是赛普拉斯的插件,可为我们提供所有可访问性测试的checkA11y() 。 再次使用axe-core插件。

To install run

安装运行

npm install cypress --save-devnpm install cypress-axe --save-dev

If it’s the first time using Cypress in your application, you will need to add the following to your package.json file under the scripts object

如果是第一次在您的应用程序中使用赛普拉斯,则需要将以下内容添加到您的scripts对象下的package.json文件中

"cypress:open": "cypress open"

This will tell our application which command needs to run to start up Cypress. Running the command you set out above will open up Cypress in a new browser with a list of test spec files.

这将告诉我们的应用程序需要运行哪个命令来启动Cypress。 运行上面列出的命令,将在带有测试spec文件列表的新浏览器中打开Cypress。

Image for post

If you go back to your editor, you will now notice there’s a cypress folder in the root of your React application. There’s one more thing we need to add under this folder to make sure all of the axe functionalities are made available to us.

如果回到编辑器,您会发现React应用程序的根目录中有一个cypress文件夹。 我们需要在此文件夹下添加另一件事,以确保所有斧头功能对我们可用。

Navigate to cypress > support > index.js and add the following:

导航至cypress>支持> index.js,然后添加以下内容:

import 'cypress-axe'

Now we’re ready to go!

现在我们准备出发了!

Under the same cypress folder, you will see integration > examples. I added a quick test under here within a new spec file:

在同一cypress文件夹下,您将看到Integration> examples 。 我在新的规范文件中的下面添加了快速测试:

/// <reference types="cypress" />


context('Demo', () => {


    beforeEach(() => {
        cy.visit('http://localhost:3001');
        cy.injectAxe();
    });




    it('should not violate any accessibility rules', () => {
        cy.checkA11y();
    });
})

Again make sure you replace the port number.

再次确保您更换了端口号。

If you now go back to the browser window containing all of the listed spec files, you should see demo-test.spec.js . Click on the file and you should see your web app on the right and your test results on the left:

如果现在返回包含所有列出的规范文件的浏览器窗口,则应该看到demo-test.spec.js 。 单击该文件,您应该在右侧看到您的Web应用程序,在左侧看到您的测试结果:

Image for post

Making a change to your source code will result in this file reloading and taking into account any fixed or new violations.

更改源代码将导致此文件重新加载,并考虑到任何固定或新的违规情况。

概要 (Summary)

Making our React web applications compliant with WCAG’s accessibility guidelines is paramount to ensuring inclusion of all types of users. With the use of ARIA attributes and screen readers, this is fairly straight forward. Checking for contrast ratio between your site’s styles has never been easier with inbuilt WCAG ratings right from within devtools. With the help of linters we’re able to see certain violations as we develop our components. React Axe makes it easy for us to see our accessibility violations and their severities via console logs within our devtools as well. To take it one step further, however, we should make use of the axe-core rules engine and the many plugins it provides to work with today’s most widely used testing frameworks.

使我们的React Web应用程序符合WCAG的可访问性指南对于确保包括所有类型的用户至关重要。 通过使用ARIA属性和屏幕阅读器,这非常简单。 使用devtools中内置的WCAG评分,检查站点样式之间的对比率从未如此简单。 在短绒棉衣的帮助下,我们在开发组件时能够看到某些违规情况。 React Ax使得我们也可以通过devtools中的控制台日志轻松查看我们的可访问性违规及其严重性。 但是,要使其更进一步,我们应该利用斧头核心规则引擎及其提供的许多插件来与当今使用最广泛的测试框架一起使用。

Are there any other accessibility checking tools you use? Let me know in the comments below, and happy coding!

您还使用其他任何可访问性检查工具吗? 在下面的评论中让我知道,祝您编程愉快!

翻译自: https://medium.com/swlh/mastering-accessibility-across-your-react-apps-f3f628a5f1fd

创建react应用程序

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值