reactjs - 如何在 React 中为表单标签生成唯一 ID?

标签 reactjs

我有带有 label 的表单元素,并且我希望有唯一的 ID 将 label 链接到带有 htmlFor 属性的元素。像这样的事情:

React.createClass({
    render() {
        const id = ???;
        return (
            <label htmlFor={id}>My label</label>
            <input id={id} type="text"/>
        );
    }
});

我曾经根据 this._rootNodeID 生成 ID,但从 React 0.13 开始就不再可用。现在最好和/或最简单的方法是什么?

最佳答案

id 应放置在 componentWillMount 内部(2018 年更新)constructor,而不是 render。将其放入 render 中将不必要地重新生成新的 id。

如果您使用下划线或 lodash,则有一个 uniqueId 函数,因此生成的代码应类似于:

constructor(props) {
    super(props);
    this.id = _.uniqueId("prefix-");
}

render() { 
  const id = this.id;
  return (
    <div>
        <input id={id} type="checkbox" />
        <label htmlFor={id}>label</label>
    </div>
  );
}

2019 年 Hooks 更新:

import React, { useState } from 'react';
import _uniqueId from 'lodash/uniqueId';

const MyComponent = (props) => {
  // id will be set once when the component initially renders, but never again
  // (unless you assigned and called the second argument of the tuple)
  const [id] = useState(_uniqueId('prefix-'));
  return (
    <div>
      <input id={id} type="checkbox" />
      <label htmlFor={id}>label</label>
    </div>
  );
}

关于reactjs - 如何在 React 中为表单标签生成唯一 ID?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29420835/

相关文章:

css - 我正在将现有的 SCSS 代码转换为 JSS,我坚持转换以下嵌套类

javascript - React-子函数调用父函数

javascript - 如何将脚本单独包含到我的构建文件夹中?

reactjs - 如何从 strip 付款表中获取 "Save Card Details"选项?

reactjs - 使用 React 显示隐藏多个元素

javascript - 如何获得直到 X 日期的天数并在 X 日期达到 0 时停止计数

javascript - 使用 React 获取 API 数据并使用自动完成功能过滤搜索输入

reactjs - React : Best practice for event propagation (trigger parent event,不是子事件)

javascript - React Redirect 不应在路由器之外使用

javascript - React 应用程序不处理键盘事件