加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-15 06:51:58 所属栏目:百科 来源:网络整理
导读:我有表单元素的标签,我想有唯一的ID来链接标签与htmlFor属性的元素。这样的东西: React.createClass({ render() { const id = ???; return ( label htmlFor={id}My label/label input id={id} type="text"/ ); }}); 我曾经基于this._rootNodeID生成ID,但
我有表单元素的标签,我想有唯一的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。

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读