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

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?

米亚Eva2020/03/12 10:18:23

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

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

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

古一阳光2020/03/12 10:18:23

您可以使用诸如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>
    );
  }   
}