简体   繁体   中英

Display random text in React app with Math.random()

I previously had embedded this JS code inside an HTML page with this:

    <SCRIPT LANGUAGE="JAVASCRIPT">
    var r_text = new Array (); 
    r_text[0] = "\"This is a test\""; 
    r_text[1] = "\"This is another\""; 
    r_text[2] = "\"This is a test\""; 
    r_text[3] = "\"This is another\""; 
    var i = Math.floor(r_text.length * Math.random()); 
    
    document.write("<center>" + 
    r_text[i]  + "</center>"); 
    </SCRIPT>

It allows me to define a bunch of sentences and have a random one displayed each time the page loads.

I am now re-doing my site as a React app (and using TailwindCSS FWIW).

I tried dropping it directly like below:

import logo from './logo.svg';
import './App.css';

function App() {
  return (
    <div class="container mx-auto">

      <div class="max-w-md mx-auto bg-white text-center text-6xl m-10 overflow-hidden md:max-w-2xl">
      site title
      </div>
    
    var r_text = new Array (); 
    r_text[0] = "\"This is a test\""; 
    r_text[1] = "\"This is another\""; 
    r_text[2] = "\"This is a test\""; 
    r_text[3] = "\"This is another\""; 
    var i = Math.floor(r_text.length * Math.random()); 
    
    document.write("<center>" + 
    r_text[i]  + "</center>"); 

This is not working, but I'm not sure how to make it compile.

In ReactJS, it is advisable to perform all calculations before rendering the content. I advise you to read the React documentation

import { useState, useEffect } from "react";

function App() {
  const [text, setText] = useState("");

  useEffect(() => {
    let r_text = new Array();
    r_text[0] = '"This is a test"';
    r_text[1] = '"This is another"';
    r_text[2] = '"This is a test"';
    r_text[3] = '"This is another"';

    var i = Math.floor(r_text.length * Math.random());
    setText(r_text[i])
  },[])

  return (
    <div class="container mx-auto">
      <div class="max-w-md mx-auto bg-white text-center text-6xl m-10 overflow-hidden md:max-w-2xl">
        site title
      </div>
      <p>{text}</p>
    </div>
  );
}

export default App;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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