繁体   English   中英

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

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

我以前将此 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>

它允许我定义一堆句子,并在每次页面加载时随机显示一个。

我现在正在将我的网站重新制作为 React 应用程序(并使用 TailwindCSS FWIW)。

我尝试直接删除它,如下所示:

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>"); 

这不起作用,但我不确定如何编译它。

在 ReactJS 中,建议在渲染内容之前执行所有计算。 我建议你阅读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