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

reactjs React.js

JinJinEva

2020-03-12

I have form elements with labels and I want to have unique IDs to link labels to elements with htmlFor attribute. Something like this:

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

I used to generate IDs based on this._rootNodeID but it’s unavailable since React 0.13. What is the best and/or simplest way to do it now?

第867篇《如何在React中为表单标签生成唯一的ID?》来自Winter(https://github.com/aiyld/aiyld.github.io)的站点

2个回答
米亚Eva 2020.03.12

如果不需要,请不要使用ID,而是将输入内容包装在这样的标签中:

<label>
   My Label
   <input type="text"/>
</label>

这样,您就不必担心唯一ID。

古一阳光 2020.03.12

您可以使用诸如node-uuid之类的库来确保获得唯一的ID。

使用以下方法安装:

npm install node-uuid --save

然后在您的react组件中添加以下内容:

import {default as UUID} from "node-uuid";
import {default as React} from "react";

export default class MyComponent extends React.Component {   
  componentWillMount() {
    this.id = UUID.v4();
  }, 
  render() {
    return (
      <div>
        <label htmlFor={this.id}>My label</label>
        <input id={this.id} type="text"/>
      </div>
    );
  }   
}

问题类别

JavaScript Ckeditor Python Webpack TypeScript Vue.js React.js ExpressJS KoaJS CSS Node.js HTML Django 单元测试 PHP Asp.net jQuery Bootstrap IOS Android