【发布时间】:2021-02-06 17:13:43
【问题描述】:
我正在尝试制作一个简单的游戏:国家/地区的国旗在屏幕上一一闪烁,并在单击按钮后停在一个特定的国旗上。
这是我目前所拥有的:
import React from 'react'
import ReactDOM from 'react-dom'
// CSS styles in JavaScript Object
const buttonStyles = {
backgroundColor: '#61dbfb',
padding: 10,
border: 'none',
borderRadius: 5,
margin: 30,
cursor: 'pointer',
fontSize: 18,
color: 'white',
}
class App extends React.Component {
constructor(props) {
super(props);
this.state = { image: 'https://www.countryflags.io/US/shiny/64.png' }
this.makeTimer()
}
makeTimer() {
setInterval(() => {
let countries = {
USA: 'https://www.countryflags.io/US/shiny/64.png',
Australia: 'https://www.countryflags.io/AU/shiny/64.png',
"Puerto Rico": 'https://www.countryflags.io/PR/shiny/64.png'
}
let currentCountry = Math.floor(Math.random() * (Object.entries(countries).map(([key, value]) => <div>{key} <img alt={key} src={value}></img></div>)))
this.setState({ currentCountry })
}, 1000)
}
stopInterval = () => {
clearInterval(this.interval);
}
render() {
return (
<div className='app'>
<h1>where are you going on vacation?</h1>
<div>{this.state.currentCountry}</div>
<button style={buttonStyles} onClick={this.stopInterval}> choose country </button>
</div>
)
}
}
const rootElement = document.getElementById('root')
ReactDOM.render(<App />, rootElement)
它不起作用,渲染的只是:
NaN
在我添加Math.floor(Math.random() * ...) 之前,它同时渲染了所有三个标志,这不是我想要的。哪里错了?
另外,我不确定计时器是否正常工作。
【问题讨论】:
-
没有阅读所有内容,但
Math.floor(Math.random())始终为零。
标签: javascript reactjs