在 React 中自动生成 Id

Auto generate Id in React

我想生成带有时间戳的自动标识,并通过反应在标签中使用它。我为 < Label >

使用了 Styled Component
// Input Error Label
 const Label = styled.label`
  color: ${theme.colors.red.default};
  padding-top: 3px;
  display: inline-block;
  font-size: 14px;
  opacity: 0.55;
  mix-blend-mode: normal;
`;


const uniqueId = () => parseInt(Date.now() * Math.random()); 

return (
   <Label id={uniqueId}>{error}</Label>  
)

为什么会报错,请看这个截图

Error Screenshot

希望这段代码对您有所帮助。

当接受的类型为 string 时,您正在尝试将 number 指定为 ID。将您的 uniqueID 函数更改为此 -

const uniqueId = () => parseInt(Date.now() * Math.random()).toString();

也用这个 -

改变你的 return 功能
return (
   <Label id={uniqueId()}>{error}</Label>  
)

可在此处查看工作代码

https://codesandbox.io/s/compassionate-zhukovsky-wr3qi?file=/src/App.js

您将 uniqueId 声明为函数并将其用作变量 第一个解决方案:调用此函数

<Label id={uniqueId()}>{error}</Label>  

第二种方案:声明为变量

const uniqueId = parseInt(Date.now() * Math.random()); 

那就不用调用了,直接当变量使用就可以了

<Label id={uniqueId}>{error}</Label>