reactjs - How can I display three random exercises from an array every time a button is pressed using React?
问题描述
I'm trying to display a list of 3 random exercises every time you press a button and change those 3 exercises on each button press
it chooses a random workout correctly in the console, but I'm not sure how to make it display and update correctly using React.
how can I make it so it displays a random 3 exercises every time the button is pressed. I've seen ways of doing it using only JS but am curious how to do this with React.
import React, { Component } from "react";
class Workout extends Component {
render() {
const upperExercises = [
"test1",
"test2",
"test3"
]
const lowerExercises = [
"test4",
"test5",
"test6"
]
const coreExercises = [
"test7",
"test8",
"test9"
]
function getAll() {
let randomUpper = upperExercises[Math.floor(Math.random() * upperExercises.length)];
console.log(randomUpper)
let randomLower = lowerExercises[Math.floor(Math.random() * lowerExercises.length)];
console.log(randomLower)
let randomCore = coreExercises[Math.floor(Math.random() * coreExercises.length)];
console.log(randomCore)
}
return (
<section>
<button onClick={() => { getAll() }}>TEST</button>
<p>DISPLAY OUTPUT</p>
</section>
)
}
}
export default Workout
解决方案
你可以尝试这样的事情。您可以从数组中随机获取值,然后设置值的值,以便您可以在<p/>
标签中轻松访问它们。
我将您的getAll
函数更改为箭头函数以避免绑定到 this 。初学者使用 Es6 箭头函数更简单。让我知道这是否有效。祝你好运!!
import React, { Component } from "react"
const upperExercises = [
"test1",
"test2",
"test3"
]
const lowerExercises = [
"test4",
"test5",
"test6"
]
const coreExercises = [
"test7",
"test8",
"test9"
]
class Workout extends Component {
constructor(props) {
super(props)
//initialise state
this.state = {
lower ='',
upper ='',
core ='',
}
}
//Changed your function to arrow function to avoid binding and its
// a simplier way of doing it
getAll = () => {
const randomUpper = Math.floor(Math.random() * upperExercises.length);
const upper = upperExercises[randomUpper]
//Get the random value and set the state to that value
this.setState({
upper: upper
})
const randomLower = Math.floor(Math.random() * lowerExercises.length);
const lower = lowerExercises[randomLower]
this.setState({
lower: lower
})
const randomCore = Math.floor(Math.random() * randomCore.length);
const core = coreExercises[randomCore]
this.setState({
core: core
})
}
render() {
return (
<section>
<button onClick={this.getAll}>TEST</button>
<p>Upper {this.state.upper}</p>
<p>Lower {this.state.lower}</p>
<p>Core {this.state.core}</p>
</section>
)
}
}
export default Workout
推荐阅读
- r - 如何在 R 上创建费率
- mobile - 需要在桌面和移动设备中打开 .ics 日历文件
- selenium - bot 检测绕过服务器上的 selenium
- python-3.x - 如何连续计数大于或等于0.5的值5或大于5行python
- html - 使用表格对齐视频并适合 div 大小
- android - 我的活动在 onResume() 之前调用 onCreate()
- python - Class() 返回错误,说不带参数
- python - 为什么语法“main.py < input.txt”不起作用
- javascript - Chrome 扩展计时器并行实例和端口连接问题
- python - 熊猫检测过日日期