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

我有带有labels的表单元素,并且我希望有唯一的ID将labels 链接到具有htmlForattribute的元素。像这样:

React.createClass({

render() {

const id = ???;

return (

<label htmlFor={id}>My label</label>

<input id={id} type="text"/>

);

}

});

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

回答:

这个解决方案对我来说很好。

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"/>

);

}

});

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

。相反,自定义NEWID的功能,您可以使用UNIQUEID从lodash。

。最好在中生成ID componentWillMount

以上是 如何在React中为表单标签生成唯一的ID? 的全部内容, 来源链接: utcz.com/qa/422554.html

回到顶部