首页 > 解决方案 > 在 React 中自动生成 ID

问题描述

我想生成带有时间戳的自动 id,并通过 react 在标签中使用它。我为 <标签> 使用了样式化组件

// 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>  
)

为什么它显示错误,请看这个截图。

错误截图

我希望这段代码有所帮助。

标签: reactjstypescriptstorybook

解决方案


当接受number的类型为string. 将您的uniqueID功能更改为此 -

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

也用这个改变你的返回功能 -

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

可以在这里看到一个工作代码

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


推荐阅读