React/jsx-a11y eslint 引发控件/标签意外错误

JES*_*Sii 3 accessibility jsx reactjs

这段代码:

      <PopupContent>
        <label htmlFor="popup" style={{ margintop : '0px', marginbottom : '0px' }}>log out</label>
        <button type="button" id="popup" onClick={this.logUserOut} />
      </PopupContent>

Run Code Online (Sandbox Code Playgroud)

抛出这两个错误:

 84:9  error  A form label must be associated with a control  jsx-a11y/label-has-associated-control
 85:9  error  A control must be associated with a text label  jsx-a11y/control-has-associated-label
Run Code Online (Sandbox Code Playgroud)

我缺少什么?

小智 7

您通常不会使用元素来标记按钮。更常见的是,按钮内的文本用作其标签。尝试一些类似的事情:

<button type="button id="popup" onClick={this.logUserOut}>log out</button>
Run Code Online (Sandbox Code Playgroud)

其他选项可以是以下任意一项:

<button type="button" id="popup" onClick={this.logUserOut} aria-label="log out"/>
Run Code Online (Sandbox Code Playgroud)

或者

<span id="button-label" style={{ margintop : '0px', marginbottom : '0px' }}>log out</span>
<button type="button" id="popup" onClick={this.logUserOut} aria-labelledby="button-label" />
Run Code Online (Sandbox Code Playgroud)

或者

<button type="button id="popup" onClick={this.logUserOut}>
    <img src="icon.png" alt="log out"/>
</button>
Run Code Online (Sandbox Code Playgroud)

或者

<button type="button id="popup" onClick={this.logUserOut}>
    <span className="off-screen">log out</span>
</button>
Run Code Online (Sandbox Code Playgroud)

其中 .off-screen 的 CSS 类以可访问的方式隐藏屏幕外的文本,例如不使用 display: none; 或可见性:隐藏;