我目前正在将我用vanilla HTML、CSS和JavaScript制作的RGB颜色猜谜游戏转换为React。
当我单击具有coloredSquare
类的六个backgroundColor中的一个时,我希望它获取该正方形的mainColor
,并将其与屏幕上显示的rgb颜色进行比较,该颜色来自具有div id的元素。
在vanilla JS中,它是如此简单,你只需要在eventListener
中执行this.style.backgroundColor
,但由于某些原因,使用React我无法理解它。我觉得自己真的很傻,我可能想得太多了,其实很简单。
代码如下:
import React, {Component} from "react";
class RGBGuesser extends Component {
constructor(){
super();
this.state = {
correctCount: 0,
displayCorrect: 0,
colors: "",
chosenResult: "",
chosenCorrect: 0,
}
}
componentDidMount = () => {
this.startGame();
}
initialGameState = () => {
this.setState({
colors: this.displayRandom(6)
})
}
restart = () => {
this.initialGameState();
this.setState({
chosenResult: "",
chosenCorrect: 0,
displayCorrect: 0
})
}
pickSquare = () => {
let colorRan = Math.floor(Math.random() * this.state.colors.length);
return this.state.colors[colorRan]
}
displayRandom = amountSquares => {
const colorArr = [];
for(let i = 0; i < amountSquares; i++){
colorArr.push(this.chooseRandom());
}
return colorArr;
}
chooseRandom = () => {
let rColor = Math.floor(Math.random() * 256);
let gColor = Math.floor(Math.random() * 256);
let bColor = Math.floor(Math.random() * 256);
return `rgb(${rColor}, ${gColor}, ${bColor})`;
}
chooseSquare = () => {
//where i would want to do the logic of clicking the square and comparing it with the rgb color displayed on screen
}
startGame = () => {
this.initialGameState();
this.restart();
}
render(){
let correctColor = this.pickSquare();
return(
<div>
<h1 id="header">RGB Color Guesser</h1>
<h3 id="mainColor">{correctColor}</h3>
<h3 id="result"></h3>
<h3 id="showCorrect">Number Correct: <span id="correctCount">0</span></h3>
<button id="startOver" onClick={this.restart}>Start Over</button>
<div id="colorGrid">
<div className="coloredSquare" onClick={this.chooseSquare} style={{backgroundColor: this.state.colors[0]}}></div>
<div className="coloredSquare" onClick={this.chooseSquare} style={{backgroundColor: this.state.colors[1]}}></div>
<div className="coloredSquare" onClick={this.chooseSquare} style={{backgroundColor: this.state.colors[2]}}></div>
<div className="coloredSquare" onClick={this.chooseSquare} style={{backgroundColor: this.state.colors[3]}}></div>
<div className="coloredSquare" onClick={this.chooseSquare} style={{backgroundColor: this.state.colors[4]}}></div>
<div className="coloredSquare" onClick={this.chooseSquare} style={{backgroundColor: this.state.colors[5]}}></div>
</div>
</div>
)
}
}
export default RGBGuesser;
https://stackoverflow.com/questions/51052546
复制相似问题