【发布时间】:2018-06-26 23:15:20
【问题描述】:
我目前正在将我用普通 HTML、CSS 和 JavaScript 制作的 RGB 颜色猜谜游戏转换为 React。
当我单击具有coloredSquare 类的六个 div 之一时,我希望它获取该正方形的背景颜色并将其与屏幕上显示的 rgb 颜色进行比较,该颜色来自具有 mainColor 的元素身份证。
在 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;
【问题讨论】:
-
发生了什么?是有错误,还是我遗漏了什么?
-
@1252748 不,没有错误。就像我说的,我不知道如何让它在点击时抓取正方形的背景颜色。
-
React 16(和 15.5)不做自动函数绑定,所以
onClick={ this.chooseSquare }需要是onClick={ evt => this.chooseSquare(evt) }你可能会注意到这也可以让你把数组索引放在对 chooseSquare 的调用中,解决你的问题。你的 render() 代码可以做一些改进,比如在返回之前生成这些 div 并将它们模板化到返回语句中。 -
@ChristianLopez 这只是反应还是原生反应?你能用一个可触摸的高光吗?它们可以绑定到函数。这是我发现的一个问题,可能对stackoverflow.com/questions/32347605/…有帮助
标签: javascript css reactjs dom-events