简体   繁体   English

在 React 中使用页面刷新生成相同的随机颜色

[英]Generate Same Random Color with Page refresh in React

In my application, I assign the same random color for the background color of the same uniqueID and I also want this color to be the same random color if the page reloads.在我的应用程序中,我为相同uniqueID的背景颜色分配了相同的随机颜色,并且如果页面重新加载,我还希望此颜色为相同的随机颜色。

My approach and current behavior is similar to the solution in this prior post: Generate Random Same Colors in React however, the colors change if the page is reloaded .我的方法和当前行为类似于之前这篇文章中的解决方案: Generate Random Same Colors in React然而,如果页面重新加载,颜色会发生变化

Question: Is there a way to map the uniqueID to a random color, and have it persist different instances of my app using REACT?问题:有没有办法将uniqueID映射到随机颜色,并让它使用 REACT 保留我的应用程序的不同实例?

See below my current code:请参阅下面我当前的代码:

function getRandomColor(): string{
  return '#' + Math.floor(Math.random()*16777215).toString(16);
}
let colorMap = new Map<number, string>();
function setColor(uniqueId: number): string{
  if(colorMap.get(uniqueId) == null){
    colorMap.set(uniqueId,getRandomColor());
  }
  return colorMapping.get(id) + "";
}
//later in the code
color: setColor(Number(d_id)),

You could use one of the various storage options to store this and then restore on each page load:您可以使用各种存储选项之一来存储它,然后在每个页面加载时恢复:

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM