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。
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP