【发布时间】:2018-05-08 10:20:18
【问题描述】:
我正在使用带有服务器渲染的 ReactJS.net。我想制作一个简单的组件,它输出一个标签和一个输入,其中标签通过 htmlFor 属性引用输入。由于该组件可以在同一页面上多次使用,因此我需要它为该组件的每个实例提供一个唯一 ID。
因此,我在构造函数中生成了一个 guid 并使用它 - 除了在服务器端和客户端都生成 ID 之外,它工作正常,这会导致值不匹配。
如何解决这种不匹配问题?
示例代码:
interface IProps { whatever:string }
export default class Test extends React.Component<IProps> {
private _guid: string;
constructor(props: IProps) {
super(props);
this._guid = Utils.getGuid(); // generates a new guid
}
render(): JSX.Element {
return (
<div>
<label htmlFor={this._guid}A nice label</label>
<input id={this._guid} type="text" />
</div>
);
}
}
代码会运行,但会产生警告:
警告:道具htmlFor 不匹配。服务器:“87d61dbe-b2a8-47bd-b299-
c6e80445f626" 客户端:"f0297b42-7781-48a4-9904-75b8fd2d1140"
【问题讨论】:
标签: javascript reactjs reactjs.net