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

我有label s的表单元素,我想要有唯一的ID链接label s与htmlFor属性的元素。 像这样的东西:

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

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

这个解决scheme对我来说很好。

utils/newid.js

 let lastId = 0; export default function(prefix='id') { lastId++; return `${prefix}${lastId}`; } 

我可以像这样使用它:

 import newId from '../utils/newid'; React.createClass({ componentWillMount() { this.id = newId(); }, render() { return ( <label htmlFor={this.id}>My label</label> <input id={this.id} type="text"/> ); } }); 

但是它在同构应用程序中不起作用。

新增17.08.2015 。 而不是定制的newId函数,你可以使用lodash中的uniqueId。

更新28.01.2016 。 在componentWillMount生成ID最好。

该id应该放在componentWillMount里面,而不是render 。 把它render将不必要地重新生成新的ID。

如果你使用下划线或lodash,则有一个uniqueId函数,所以你的结果代码应该是这样的:

 componentWillMount() { const id = _.uniqueId("prefix-"); this.setState({id: id}); } render() { const id = this.state.id; return ( <div> <input id={id} type="checkbox" /> <label htmlFor={id}>label</label> </div> ); } 

有很多“胶带”解决scheme。 一个是https://github.com/DelvarWorld/Unique-Id-Mixin

希望这有助于任何人寻找一个通用/同构的解决scheme,因为校验和问题是首先引起我的。

如上所述,我创build了一个简单的实用程序,以顺序创build一个新的ID。 由于ID在服务器上不断增加,并且从客户端重新开始,所以我决定在每个SSR开始时重新设置增量。

 // utility to generate ids let current = 0 export default function generateId (prefix) { return `${prefix || 'id'}-${current++}` } export function resetIdCounter () { current = 0 } 

然后在根组件的构造函数或componentWillMount中,调用reset。 这基本上重置每个服务器呈现中的服务器的JS范围。 在客户端它不(也不应该)有任何作用。

我更喜欢让反应自动生成的ID 。 我不完全确定这是否正确的使用,因为下划线通常是私人的,但它的确有用。

this._reactInternalInstance._rootNodeID

 render () { <button id={this._reactInternalInstance._rootNodeID}> {this.props.children} {/*tooltip */} <div htmlFor={this._reactInternalInstance._rootNodeID} className="mdl-tooltip mdl-tooltip--large"> {this.props.children} </div> </button> } 

你可以使用一个库,如node-uuid来确保你获得唯一的id。

安装使用:

npm install node-uuid –save

然后在你的反应组件中添加以下内容:

 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> ); } }