Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
318 views
in Technique[技术] by (71.8m points)

javascript - Problems generating random classNames for HTML tags in React

Hello everyone!

This might be a silly question but I can't figure out why the className variable in the console.log has a different value from the one used in the className attribute of the <p>.

I'm trying to generate random class names for HTML tags so then I can create CSSStyleSheets with rules to these HTML tags. Since, in this example, the css prop is the same the styling is working but the className variables in the tag and in console.log are different and that's what I can't understand why.

Am I missing something obvious or is this somehow the intended behaviour?

The code is this:

import React from 'react'

const constructCss = (css) => {
  const style = document.createElement('style')
  document.head.appendChild(style)
  style.appendChild(document.createTextNode(css))
}

const constructCssStyleAndReturnClassName = (css) => {
  const generateRandomString = (length=6) => Math.random().toString(20).substr(2, length)
  const className = `styled-${generateRandomString(8)}`
  constructCss(`.${className} ${css}`)
  return className
}

const Pa = ({css, children}) => {
  const className = constructCssStyleAndReturnClassName(css)
  console.log('Rendering with className: ', className)
  return <p className={className}>{children}</p>
}

export default function App() {
  return (
    <div className="App">
      <Pa css={`{ background-color: blue; color: white }`}>Helloooooo</Pa>
    </div>
  );
}

It's also here in codesandbox

Thanks in advance :)

question from:https://stackoverflow.com/questions/65847325/problems-generating-random-classnames-for-html-tags-in-react

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The Code Sandbox seems too slow to catch it with console.log, but if you set a debugger (or console.count) in your Pa component you will see that you get 2 renders, which means you get two different random class names. I would guess that it logs the first, but then uses the second.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...