如何在React中使用单击事件创建随机数

发布于 2025-02-03 01:04:26 字数 647 浏览 2 评论 0原文

单击按钮时,我想创建从1到50的随机数。因此,这是我的组成部分:

import React from 'react'
import './Board.css';

const Board = () => {
    let rand;
    function createNumber() {
        rand = Math.floor(Math.random() * 50) + 1;
    }
    return (
        <div className="game-board">
            <div id="selected-number">
                <h1 className="bingo-ball__text">{rand}</h1>
                <button className="button button3" onClick={createNumber}>Select Number</button>
            </div>
        </div>
    )
}

export default Board

但是当我单击时,我无法得到任何响应(因此我在此内部看不到任何{rand})或错误。

I want to create random numbers from 1 to 50 when I click the button. So here is my component for this:

import React from 'react'
import './Board.css';

const Board = () => {
    let rand;
    function createNumber() {
        rand = Math.floor(Math.random() * 50) + 1;
    }
    return (
        <div className="game-board">
            <div id="selected-number">
                <h1 className="bingo-ball__text">{rand}</h1>
                <button className="button button3" onClick={createNumber}>Select Number</button>
            </div>
        </div>
    )
}

export default Board

But when I click, I cannot get any response (so I dont see anything inside of this {rand}) or error.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

多孤肩上扛 2025-02-10 01:04:26

您应该使用React Hook USESTATE,以便在生成新的随机数字时重新渲染类似So:

import "./styles.css";
import { useState } from "react";

export default function App() {
  const [rnd, setRnd] = useState(0);

  return (
    <div className="App">
      <h1>Hello CodeSandbox</h1>
      <button onClick={() => setRnd(Math.floor(Math.random() * 50))}>
        gen randomn num
      </button>
      <div>{rnd}</div>
    </div>
  );
}

示例: https://codesandbox.io/s/black-pine-5sgxxw?file = file =/src/src/app.js: 0-349

You should use the react hook useState so that your component gets re-rendered when you generate a new random numer like so:

import "./styles.css";
import { useState } from "react";

export default function App() {
  const [rnd, setRnd] = useState(0);

  return (
    <div className="App">
      <h1>Hello CodeSandbox</h1>
      <button onClick={() => setRnd(Math.floor(Math.random() * 50))}>
        gen randomn num
      </button>
      <div>{rnd}</div>
    </div>
  );
}

Example: https://codesandbox.io/s/black-pine-5sgxxw?file=/src/App.js:0-349

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文