【问题标题】:Get backgroundColor of an element onClick in React在 React 中获取元素 onClick 的背景颜色
【发布时间】: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 =&gt; this.chooseSquare(evt) } 你可能会注意到这也可以让你把数组索引放在对 chooseSquare 的调用中,解决你的问题。你的 render() 代码可以做一些改进,比如在返回之前生成这些 div 并将它们模板化到返回语句中。
  • @ChristianLopez 这只是反应还是原生反应?你能用一个可触摸的高光吗?它们可以绑定到函数。这是我发现的一个问题,可能对stackoverflow.com/questions/32347605/…有帮助

标签: javascript css reactjs dom-events


【解决方案1】:
    chooseSquare = (e) => {
      console.log(e.currentTarget.style.background)
    }

我认为将事件传递给您的事件处理程序和 currentTarget \ target 是您所缺少的

别忘了在构造函数中绑定事件处理程序! constructor() { // snip this.chooseSquare = this.chooseSquare.bind(this); }

【讨论】:

  • 当我在chooseSquare 中尝试console.log(e.currentTarget.style.background) 时,它返回错误“无法读取未定义的属性'currentTarget'”编辑:等等,没关系,它不再那样做了。我会尝试使用它,看看我是否可以让它工作。
  • 嘿,这行得通。非常感谢!另外,如果我错了,请纠正我,但我认为我不需要绑定它,因为我使用的是箭头函数。它无需绑定即可工作。
  • 是的,你是对的——你不需要显式绑定。我没有仔细研究你是如何定义你的函数的:)
猜你喜欢
  • 1970-01-01
  • 2013-05-29
  • 2010-12-25
  • 1970-01-01
  • 1970-01-01
  • 2013-07-22
  • 1970-01-01
  • 1970-01-01
  • 2012-01-30
相关资源
最近更新 更多