Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

css - How to generate a random number each time a component re-renders?

I want to use Less variables to generate a random number for conditionally class that gets added and removed each second. Here is the sample code of reactjs file

function App() {
  const [date , setDate] = useState('')
  const [circleBoolean, setCircleBoolean] = useState(false);
  const [random_number, setRandom_number] = useState(0);
  
  useEffect(() => {
    const interval = setInterval(() => {
      doThings()
    }, 1000);
    return () => clearInterval(interval);
  }, []);

  function doThings() {
    setCircleBoolean((prev)=>{
      return !prev});
    setDate(moment().format('MMMM Do YYYY, h:mm:ss a')) ;
    setRandom_number(Math.random() * 100);
    console.log("cirlce boolean :" + circleBoolean)
  }



  return (
    <div className="App">
      <div className="bg">
        <div style={{ top:`${random_number}%`, left:`${random_number}%` }}  className={circleBoolean ? "circle" : ""} />
        <div className="card">
          <p className="card-info">{date}</p>
        </div>
      </div>
    </div>
  );
}

and here is the sample code from css file

@color: blue;
@random: (round(`Math.random()`)) ;

.circle {
  position: absolute;
  border: solid 4px @color;
  border-radius: 50%;
 
  height: @random;
  width: 3em;
  background-color: @color;
  animation: circleSize 1s ease-in-out;
}

@keyframes circleSize {
  0% {
    transform: scale(0, 0);
  }
  50% {
    transform: scale(1,1);
  }
  100%{
    transform: scale(0,0);
  }
}

The random number is generated only during the first render and is not changed during subsequent re-renders. How do I go about it ?

question from:https://stackoverflow.com/questions/65641863/how-to-generate-a-random-number-each-time-a-component-re-renders

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

1 Reply

0 votes
by (71.8m points)

My advice is use a 'css-in-js' approach. React only re-renders components that changed and your css is static right now. If you define your styles in a js file and pass your random number to this file every time your App's interval runs - you'll get your re-renders.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...