如何在 React 中为表单标签生成唯一 ID? [英] How to generate unique IDs for form labels in React?

查看:61
本文介绍了如何在 React 中为表单标签生成唯一 ID?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有带有 label s 的表单元素,我希望有唯一的 ID 将 labels 链接到带有 htmlFor 属性的元素.像这样:

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

我曾经根据 this._rootNodeID 生成 ID,但从 React 0.13 开始就无法使用了.现在最好和/或最简单的方法是什么?

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?

推荐答案

这个解决方案很适合我.

This solutions works fine for me.

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

但它不适用于同构应用.

But it won’t work in isomorphic apps.

2015 年 8 月 17 日添加.您可以使用 lodash 的 uniqueId 代替自定义 newId 函数.

Added 17.08.2015. Instead of custom newId function you can use uniqueId from lodash.

2016 年 1 月 28 日更新.最好在componentWillMount中生成ID.

这篇关于如何在 React 中为表单标签生成唯一 ID?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆