簡體   English   中英

我如何更改a的文本<p>在 React.js 中使用按鈕?

[英]How do I change the text of a <p> with a button in React.js?

為了我的娛樂和練習,我正在制作一個簡單的隨機侮辱生成器。 我計划將我的元素分離成組件並干燥代碼。 我正在嘗試制作一個event handler ,它將用一個新的隨機單詞更新我的<p>元素的文本。 我嘗試在App組件中添加一個函數,並且'button clicked'console.log成功。 如何獲取<p className="randomInsultText">並在那里顯示隨機文本?

import React from "react";
import "./App.css";
import image from "./callthema.png";
import words from "./data";


function App() {
  return (
    <div className="App">
      <>
        <img src={image} alt="meme" width="50%" />
        <h2>Call em' a</h2>

        <p className="randomInsultText">
          {words[0].setOne[Math.floor(Math.random() * words[0].setOne.length)] +
            " " +
            words[1].setTwo[Math.floor(Math.random() * words[1].setTwo.length)]}
        </p>
     <button>New Word</button>
      </>
    </div>
  );
}

export default App;

這是我的 data.js 文件中單詞的縮寫版本:

export default [
  {
    setOne: ["Lazy", "Smelly", "Egg Headed", "Terrible"]
  },
  {
    setTwo: ["Goblin", "Dingbat", "Lunkhead", "Snowflake"]
  }
];

您應該使用state將值更新到react應用程序中。 React functional component有一個很棒的hook叫做useState 你可以試試這個。

const [word, setWord] = useState(words[0].setOne[Math.floor(Math.random() * words[0].setOne.length)] + " " + words[1].setTwo[Math.floor(Math.random() * words[1].setTwo.length)]);


<p className="randomInsultText">{word}</p>
<button onClick={setWord(words[0].setOne[Math.floor(Math.random() * words[0].setOne.length)] + " " + words[1].setTwo[Math.floor(Math.random() * words[1].setTwo.length)])}>New Word</button>

你可以使用所謂的hooks

import React, { useState } from "react"
import "./App.css"
import image from "./callthema.png"
import words from "./data"

const App = () => {
  const [insult, setInsult] = useState(
    words[0].setOne[Math.floor(Math.random() * words[0].setOne.length)] +
      " " +
      words[1].setTwo[Math.floor(Math.random() * words[1].setTwo.length)]
  )

  const randomizeInsult = () => {
    setInsult(
      words[0].setOne[Math.floor(Math.random() * words[0].setOne.length)] +
        " " +
        words[1].setTwo[Math.floor(Math.random() * words[1].setTwo.length)]
    )
  }
  return (
    <div className="App">
      <>
        <img src={image} alt="meme" width="50%" />
        <h2>Call em' a</h2>

        <p className="randomInsultText">{insult}</p>
        <button onClick={() => randomizeInsult()}>New Word</button>
      </>
    </div>
  )
}

export default App

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM