我有带有 label
的表单元素,并且我希望有唯一的 ID 将 label
链接到带有 htmlFor
属性的元素。像这样的事情:
React.createClass({
render() {
const id = ???;
return (
<label htmlFor={id}>My label</label>
<input id={id} type="text"/>
);
}
});
我曾经根据 this._rootNodeID
生成 ID,但从 React 0.13 开始就不再可用。现在最好和/或最简单的方法是什么?
最佳答案
id 应放置在 componentWillMount 内部(2018 年更新)constructor
,而不是 render
。将其放入 render
中将不必要地重新生成新的 id。
如果您使用下划线或 lodash,则有一个 uniqueId
函数,因此生成的代码应类似于:
constructor(props) {
super(props);
this.id = _.uniqueId("prefix-");
}
render() {
const id = this.id;
return (
<div>
<input id={id} type="checkbox" />
<label htmlFor={id}>label</label>
</div>
);
}
2019 年 Hooks 更新:
import React, { useState } from 'react';
import _uniqueId from 'lodash/uniqueId';
const MyComponent = (props) => {
// id will be set once when the component initially renders, but never again
// (unless you assigned and called the second argument of the tuple)
const [id] = useState(_uniqueId('prefix-'));
return (
<div>
<input id={id} type="checkbox" />
<label htmlFor={id}>label</label>
</div>
);
}
关于reactjs - 如何在 React 中为表单标签生成唯一 ID?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29420835/