我有表单元素的标签,我想有唯一的ID来链接标签与htmlFor属性的元素。这样的东西:
React.createClass({ render() { const id = ???; return ( <label htmlFor={id}>My label</label> <input id={id} type="text"/> ); } });
我曾经基于this._rootNodeID生成ID,但是从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"/> ); } });
但它不会在同构应用程序中工作。
添加17.08.2015。而不是自定义newId函数,你可以使用uniqueId从lodash。
更新时间:2012年8月16日最好在componentWillMount中生成ID。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。