Javascript 单击React可获取元素的背景色

Javascript 单击React可获取元素的背景色,javascript,css,reactjs,dom-events,Javascript,Css,Reactjs,Dom Events,我目前正在将我用香草HTML、CSS和JavaScript制作的RGB颜色猜测游戏转换为React 当我单击带有类coloredSquare的六个div中的一个时,我想让它抓取该正方形的背景色,并将其与屏幕上显示的rgb颜色进行比较,该颜色来自具有mainColorid的元素 在vanilla JS中,它非常简单,您只需在eventListener的内部执行这个.style.backgroundColor,但由于React的某些原因,我无法理解它。我觉得自己真的很笨,我可能想得太多了,其实很简单

我目前正在将我用香草HTML、CSS和JavaScript制作的RGB颜色猜测游戏转换为React

当我单击带有类
coloredSquare
的六个div中的一个时,我想让它抓取该正方形的背景色,并将其与屏幕上显示的rgb颜色进行比较,该颜色来自具有
mainColor
id的元素

在vanilla JS中,它非常简单,您只需在
eventListener
的内部执行
这个.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;
import React,{Component}来自“React”;
类RGBGuesser扩展组件{
构造函数(){
超级();
此.state={
更正计数:0,
显示正确:0,
颜色:“,
chosenResult:“,
chosenCorrect:0,
}
}
componentDidMount=()=>{
这个;
}
初始游戏状态=()=>{
这是我的国家({
颜色:此。显示随机(6)
})
}
重新启动=()=>{
this.initialGameState();
这是我的国家({
chosenResult:“,
chosenCorrect:0,
显示正确:0
})
}
pickSquare=()=>{
让colorRan=Math.floor(Math.random()*this.state.colors.length);
返回此.state.colors[colorRan]
}
displayRandom=amountSquares=>{
常量colorArr=[];
for(设i=0;i{
设rColor=Math.floor(Math.random()*256);
设gColor=Math.floor(Math.random()*256);
设bColor=Math.floor(Math.random()*256);
返回`rgb(${rColor},${gColor},${bColor})`;
}
选择方形=()=>{
//在这里,我想做的逻辑是单击正方形并将其与屏幕上显示的rgb颜色进行比较
}
StartName=()=>{
this.initialGameState();
这是restart();
}
render(){
让correctColor=this.pickSquare();
返回(
RGB颜色猜测器
{correctColor}
正确数字:0
重新开始
)
}
}
导出默认RGBGuesser;
我认为将事件传递到事件处理程序和
currentTarget
\
target
是您缺少的

另外,不要忘记在构造函数中绑定事件处理程序!

构造函数(){
//剪断
this.chooseSquare=this.chooseSquare.bind(this);
}

发生了什么事?是有错误,还是我遗漏了什么?@1252748不,没有错误。就像我说的,我不知道如何让它抓取正方形onClick.React 16(和15.5)的背景色,不做自动函数绑定,所以
onClick={this.chooseSquare}
需要
onClick={evt=>this.chooseSquare(evt)}
您可能会注意到,这还允许您将该数组索引放入对chooseSquare的调用中,从而解决您的问题。您的render()代码可以做一些改进,比如在返回之前生成这些div,并将它们模板化到returns语句中。@ChristianLopez这是react还是react native?你能用一个可触摸的高光吗?它们可以绑定到函数。。当我尝试
console.log(e.currentTarget.style.background)
在chooseSquare内部时,我发现一个问题可能会有所帮助。它返回一个错误“无法读取未定义的属性'currentTarget'”编辑:等等,不管怎样,它不再这样做了。我会试着用这个,看看能不能用。嘿,这个有用。非常感谢!另外,如果我错了,请纠正我,但我不认为我需要绑定它,因为我使用的是arrow函数。它在没有绑定的情况下工作。是的,你是对的——你不需要显式绑定。我没有仔细查看您是如何定义函数的:)
    chooseSquare = (e) => {
      console.log(e.currentTarget.style.background)
    }