javascript - 使用 Math.random() 在 React 应用程序中显示随机文本
问题描述
我之前已经将此 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;
推荐阅读
- flutter - Flutter 给出了 Unexpected character: Undefined location error while working with graphql
- python - 如何使用 tensorflow 2.0 计算中位数?
- json - jq 命令返回 null
- c - 头文件中结构定义的编译器错误
- vb.net - 从字符串的整数更改字段
- node.js - 如何读取我在 Heroku 上写入的 JSON 文件?
- java - 在一个具体类中定义所有抽象方法
- python - 在 Ipython Notebook 中查看打印输出的所有行
- java - 启动单例 bean 可以延迟 J2EE 容器初始化吗?
- java - 优化数组的分区