如何在React中使用单击事件创建随机数
单击按钮时,我想创建从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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您应该使用React Hook
USESTATE
,以便在生成新的随机数字时重新渲染类似So:示例: 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:Example: https://codesandbox.io/s/black-pine-5sgxxw?file=/src/App.js:0-349