无法在React应用中禁用指针事件

3
我正在制作一个Simon游戏,其中有四个季度圆形,所有的圆形都有类名“colorButton”:红色、黄色、蓝色和绿色。
我希望在电脑回合时,禁用所有指向这四个彩色圆形的指针事件,以便您不能点击它们。
在我的代码中,我使用:
const colorButtons = document.getElementsByClassName('colorButton');
      colorButtons.style.pointerEvents = 'none';

但是我收到了这个控制台错误:
Uncaught TypeError: Cannot set property 'pointerEvents' of undefined
    at App.computerMove (http://localhost:8080/bundle.js:14010:42)
    at App.startGame (http://localhost:8080/bundle.js:13997:14)

我在这里做错了什么吗?

全部代码如下:

import React, { Component } from 'react';

import ColorButton from './colorbutton';

export default class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      powerOn: false,
      start: false,
      myTurn: false,
      compMoves: ['red', 'yellow', 'blue', 'green'],
      myMoves: [],
      count: null
    };
    this.colors = ['green', 'red', 'yellow', 'blue'];
    this.powerOn = this.powerOn.bind(this);
    this.startGame = this.startGame.bind(this);
    this.highlightBtn = this.highlightBtn.bind(this);
    this.computerMove = this.computerMove.bind(this);
  }

  startGame() {
    const { powerOn } = this.state;
    if (powerOn) {
      this.setState({ start: true });
      this.computerMove();
    }
  }

  computerMove(){
    if (!this.state.myTurn) {
      const randNum = Math.floor(Math.random() * 4);
      const randColor = this.colors[randNum];
      const count = this.state.count;

      const colorButtons = document.getElementsByClassName('colorButton');
      colorButtons.style.pointerEvents = 'none';

      const compMoves = this.state.compMoves.slice();
      compMoves.push(randColor);

      var i=0;
      const repeatMoves = setInterval(() => {
        this.highlightBtn(compMoves[i]);
        i++;
        if (i >= compMoves.length) {
          clearInterval(repeatMoves);
        }
      }, 1000);

      this.setState({
        compMoves: compMoves,
        myTurn: true,
        count: count + 1
      });
    }
  }

  highlightBtn(color) {
    const audio = document.getElementById(color+'Sound');
    audio.play();

    const selectColor = document.getElementById(color);
    selectColor.style.opacity = 0.5;
    setTimeout(() =>{ selectColor.style.opacity = 1}, 200);
  }

  powerOn(event) {
    const { powerOn } = this.state;
    if (!powerOn) { this.setState({ powerOn: true }) }
    else { this.setState({ powerOn: false }) }
  }

  render() {
    console.log('moves:', this.state.compMoves);
    const { count } = this.state;

    return(
      <div className='container'>
        <div className='outer-circle'>
          <ColorButton
            color='green'
            handleClick={() => this.highlightBtn('green')}
          />
          <ColorButton
            color='red'
            handleClick={() => this.highlightBtn('red')}
           />
          <ColorButton
            color='yellow'
            handleClick={() => this.highlightBtn('yellow')}
          />
          <ColorButton
            color='blue'
            handleClick={() => this.highlightBtn('blue')}
          />
          <div className='inner-circle'>
            <h2>Simon®</h2>
            <div className='count-box'>
              <div className='count-display'>{count ? count : '--'}</div>
              <div className='small-text'>Count</div>
            </div>
          </div>
        </div>
        <div className='controls'>
          <div className='power-box'>
            <div className='power-text'>OFF</div>
            <label className="switch">
              <input type="checkbox" onChange={this.powerOn}/>
              <div className="slider round"></div>
            </label>
            <div className='power-text'>ON</div>
          </div>
          <div className='buttons'>
            <div className='start-box'>
              <div className='start-button' onClick={this.startGame}></div>
              <div className='small-text'>Start</div>
            </div>
            <div className='strict-box'>
              <div className='strict-button'></div>
              <div className='small-text'>Strict</div>
            </div>
          </div>
        </div>

        <p className='footer'>
          Source code on <a href='https://github.com/drhectapus/react-simon-game'>Github</a>
        </p>
      </div>
    )
  }
}
1个回答

8
你的错误原因是getElementsByClassName返回一个类似数组的对象,因此它没有style属性。因此,colorButtons.style是未定义的,colorButtons.style.pointerEvents导致了你的错误。
我还要指出的是,你的一般方法相当不符合React的思想。你几乎从不想直接改变DOM。使用React,你只需根据props和state定义组件应该如何呈现。直接更改DOM的一个大问题是,每次重新渲染时,你的更改都将被清除。我建议你尝试使用类似以下的方法来处理你想要做的事情:
<ColorButton
  color='green'
  disabled={ !this.state.myTurn }
  handleClick={() => this.highlightBtn('green')}
/>

class ColorButton extends Component {
  render() {
    return (
      <div style={{ pointerEvents: this.props.disabled ? 'none' : 'auto' }}>
        ...
      </div>
    )
  }
}

谢谢你的建议 - 我明白你的意思了。我没有想到可以通过样式属性来操作DOM。在我的 highlightBtn(color) 函数中,我是否犯了同样的错误? - doctopus
是的,在那里也应该避免这样做。你几乎永远不会想在组件中查询和更新DOM。相反,更新状态将触发重新渲染以进行更新。 - TLadd

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接