简体   繁体   English

使用 Math.random() 在 React 应用程序中显示随机文本

[英]Display random text in React app with Math.random()

I previously had embedded this JS code inside an HTML page with this:我以前将此 JS 代码嵌入到 HTML 页面中,如下所示:

    <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).我现在正在将我的网站重新制作为 React 应用程序(并使用 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.在 ReactJS 中,建议在渲染内容之前执行所有计算。 I advise you to read the React documentation我建议你阅读React 文档

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;

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

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