[ARIA] Read error message for the focused form field by using aria-describedby

Labeling inputs, elements, and widgets add context and clarity for assistive technology such as screen readers. Beyond adding accessible labels to elements and widgets we can also provide additional descriptions. Similar to how an aria-labelledby attribute works, an aria-describedby attribute can link the text from another element or elements to be used as a description for the given element.

Some example use cases for using an aria-describedby are:

  • providing instructions
  • providing important usage details

First we can add 'id' for the error message

// src/primitives/FormInput.js
const helperId = helperText ? `${name}-helper` : ''
const errorId = errorText && !isValid ? `${id}-error` : ''
..
// src/primitives/FormInput.js
{
  helperText && (
    <small id={helperId} className="form-text text-muted helper-text">
      {helperText}
    </small>
  )
}

..

{
  errorText && (
    <div id={errorId} className="invalid-feedback">
      {errorText}
    </div>
  )
}

Then for the input field, we can use aira-describedby

// src/primitives/FormInput.js
<input
  id={id}
  type={type}
  name={name}
  className={inputClasses}
  onChange={onChange}
  aria-describedby={`${helperId} ${errorId}`}
/>

All code in React syntax

原文地址:https://www.cnblogs.com/Answer1215/p/12617266.html