React.js 中的可访问性
html 元素上的 aria-* 属性在 React.js 中也受支持。其他属性通常以驼峰形式编写,而 aria-* 以连字符形式编写。
<input type = "text" aria-label = {labelText} aria-required = "true" onChange = {changeHandler} value = {inputValue} name = "userInput" />
如果我们在 React.js 中使用父 div,有时会破坏 html 的语义
示例
render(){ return( <div> <h1>Test</h1> </div> ); }
与表格、列表等一起使用时,div 会导致语义问题。为避免这种情况,我们可以使用 React 提供的片段,如下所示 −
import React, { Fragment } from ‘react’; function MessageList({ message }) { return ( <Fragment> <dt>{ message.key }</dt> <dd>{message.description}</dd> </Fragment> ); }
我们还可将其用于将一组项目映射到一片段数组 −
function MessageList(props) { return ( <dl> {props.messages.map( message => ( // Fragments should also have a `key` prop when mapping collections <Fragment key = { message.id}> <dt>{message.from}</dt> <dd>{message.To}</dd> </Fragment> ))} </dl> ); }
片段的简短语法仅编写为 >>
import React, { Fragment } from ‘react’; function MessageList({ message }) { return ( <> <dt>{ message.key }</dt> <dd>{message.description}</dd> </> ); }
表单中的标签
我们不要在标签的 for 属性中编写,而是将其写为 htmlFor
<label htmlFor = "userID">Name:</label> <input id = "userID" type = "text" name = "name"/>
使用 ref 控件焦点 −
我们可以创建 ref 为 −
This.userInput = React.createRef(); getFocus() { // Explicitly focus the text input using the raw DOM API // Note: we're accessing "current" to get the DOM node this.userInput.current.focus(); }
要通过高阶组件操作 ref,则需要使用转发 ref。
广告