我以前將此 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>");
這不起作用,但我不確定如何編譯它。
uj5u.com熱心網友回復:
在 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;
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/336574.html
標籤:javascript 反应
上一篇:將元素平滑縮放到零然后恢復到其原始大小的正確方法是什么
下一篇:如何在反應中為UI設定影片?
