reactjs - 在 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>
)
为什么它显示错误,请看这个截图。
我希望这段代码有所帮助。
解决方案
当接受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
推荐阅读
- python - 列表语法说明中的条件语句
- android - 依赖应用配置 Wear Os, gradle vs manifest for distribution
- flutter - 我在 cli 中找不到创建自定义启动应用程序
- php - 从数组中最频繁的值中获取键,如果有值“tie”,则获取最高的键
- xcode - Xcode 项目文件在提交时总是被修改
- apache - htaccess - 带有多个变量的漂亮 url
- python - 在 Python 中抓取多个页面
- swift - 为什么 xcode 不允许我使用 actionCodeSettings(直接从 firebase 文档复制并替换为我的信息)?
- css - webkit-text-fill-color 的 Safari 问题
- scala - 迭代 CompactBuffer——Spark 和 Scala