react 中 动态添加 class,防止图片 重复加载, 主要是 background-image的二次加载会有新请求,和图片的闪烁

react 中 动态添加 class,防止图片 重复加载, 主要是 background-image的二次加载会有新请求,和图片的闪烁

let imageTopBg
  if (imgSrcBg) {
    const imgSrcBgHeight1 = imgSrcBgHeight ? imgSrcBgHeight : '98px'
    const cn = defineCss(`${imgSrcBg.replace('.', '')}ClassName`, `
        background-image: url("./uploads/images/${imgSrcBg}");
        height: ${imgSrcBgHeight1};
        border-radius: 3px 3px 0 0;
    `)
    imageTopBg = (
      <div className={cn}></div>
    )
  }

const defineCss = (className, styleBlock) => {
  const exist = document.getElementById(className)
  console.info('exist', exist)
  if (!exist) {
    const styleEl = document.createElement('style')
    styleEl.id = className
    styleEl.textContent = `
      .${className} {
        ${styleBlock}
      }
    `
    document.head.appendChild(styleEl)
  }
  return className
}