Form.Item和Radio.Group结合使用,出现Incorrect use of <label for=FORM_ELEMENT>

2024年06月18日 02:35  ·  阅读 374

1、问题

使用react结合antD的Form.Item时,在Chrome中出现如下错误(项目可以运行,但是控制台会出错):

The label's for attribute doesn't match any element id. This might prevent the browser from correctly autofilling the form and accessibility tools from working correctly.

To fix this issue, make sure the label's for attribute references the correct id of a form field.

看了一下报错的地方的代码如下:

          <Form.Item label="状态" name="status">
            <Radio.Group name="status">
              <Radio value={null}>全部</Radio>
              <Radio value={0}>草稿</Radio>
              <Radio value={1}>待审核</Radio>
              <Radio value={2}>审核通过</Radio>
              <Radio value={3}>审核失败</Radio>
            </Radio.Group>
          </Form.Item>

2、环境

   "react": "^18.3.1"

   "antd": "^5.18.1"

3、原因分析

解决问题之前,先了解一下label的for属性,主要是通过for和元素的id建立label和元素的关系。

3.1、label的for属性介绍

<label>通过for属性和组件的id进行匹配,两者相同时,建立匹配关系。

  • 显示建立关系
<div class="preference">
  <label for="cheese">Do you like cheese?</label>
  <input type="checkbox" name="cheese" id="cheese" />
</div>

<div class="preference">
  <label for="peas">Do you like peas?</label>
  <input type="checkbox" name="peas" id="peas" />
</div>
  • 隐式建立关系

<input> 放在<label内容>,可以隐式地建立两者的关系。此时for和id都不需要了。

<label>
  Do you like peas?
  <input type="checkbox" name="peas" />
</label>

label标签的for属性还具有如下性质:

①、label最多只能和一个元素匹配;

②、label只能匹配特定的元素类型(<button>、<input>(type=“hidden”除外)、<meter>、<output>、<progress>、<select>和<textarea>。

③、label在document中匹配到第一个id之后,也不再继续匹配其他的id了。即使第一个id的元素不是②中的元素,此时for无效。

3.2、原因分析

<Form.Item label="状态" name="status">最终被解释成了如下语句:产生了一个<label for="status">和<div id="status">。

经过上面的分析,label和RadioGroup通过for和id建立了关联,但是Radio.Group不是label可以匹配的元素类型,因此报错。

1718688017574.jpg

4、解决方法

4.1、生成一个匹配的元素(不推荐)

此处使用htmlFor明确for属性的值,而不是由name隐式产生。

建立一个hidden的标签,规避掉这个错误。

          <Form.Item label="状态" name="status" htmlFor='.MEANING_LESS_PLACE_HOLDER'>
            <Radio.Group>
              <Radio value={null}>全部</Radio>
              <Radio value={0}>草稿</Radio>
              <Radio value={1}>待审核</Radio>
              <Radio value={2}>审核通过</Radio>
              <Radio value={3}>审核失败</Radio>
            </Radio.Group>
            <button id='.MEANING_LESS_PLACE_HOLDER' hidden />
          </Form.Item>

4.2、显示地指定元素匹配

其实每个Radio应该有一个id值,因此可以用第一个Radio的id去匹配for属性。

          <Form.Item label="状态" name="status" htmlFor='status-radio'>
            <Radio.Group>
              <Radio id='status-radio' value={null}>全部</Radio>
              <Radio id='status-radio-0' value={0}>草稿</Radio>
              <Radio id='status-radio-1' value={1}>待审核</Radio>
              <Radio id='status-radio-2' value={2}>审核通过</Radio>
              <Radio id='status-radio-3' value={3}>审核失败</Radio>
            </Radio.Group>
          </Form.Item>

label资料链接:

https://developer.mozilla.org/en-US/docs/Web/HTML/Element/label

评论
全部评论