下面的反应示例仅展示了带有 VoiceOver 的 Firefox 上的意外行为。
使用aria-live
此标签上的属性p
,我希望我的屏幕阅读器在文本更新时能够阅读我的文本。但是,我的屏幕阅读器没有阅读我更新的文本。我使用的屏幕阅读器是 macbook 上的 VoiceOver。
我用 html 和 vanilla JS 创建了同一个小应用程序,它按预期工作。代码和codepen链接如下...
如果您使用的是 Mac 并且以前从未这样做过,请按住 command 并按 touchID 3 次以启动 VoiceOver。
这是我的反应代码...链接到 codepen
// jsx
const App = () => {
const [text, setText] = React.useState('hello')
const handleClick = () => {
if(text === 'hello') {
setText('goodbye')
} else {
setText('hello')
}
}
return (
<div>
<p aria-live="polite">{text}</p>
<button
type="button"
onClick={handleClick}
>
click
</button>
</div>
)
}
ReactDOM.render(<App />,
document.getElementById("root"))
<!-- html -->
<div id="root"></div>
...这是我预期的 html/vanilla JS 代码...链接到 codepen
<!-- html -->
<div>
<p aria-live="polite" id="text">hello</p>
<button
type="button"
id="btn"
>
click here
</button>
</div>
<script>
const text = document.getElementById('text');
const btn = document.getElementById('btn');
function handleClick() {
if (text.innerText === 'hello') {
text.innerText = 'goodbye';
} else {
text.innerText = 'hello';
}
}
btn.addEventListener('click', handleClick);
</script>