反应 - 相邻元素的切换颜色

时间:2017-11-13 03:46:03

标签: javascript reactjs ecmascript-6

我创建了一个gameBoard,并且无法切换按钮div的背景颜色。切换适用于单击"按钮" (样式div),但当我点击相邻按钮时,它需要两次点击才能获得下一个按钮来更改其背景颜色。如何在第一次单击时切换相邻按钮?我已经阅读了一些相关的帖子,如(Changing style of a button on click),但仍然在努力让这项工作成功 -

以下相关代码, 完整代码:https://jsfiddle.net/lydiademi/kt2qgfpr/

TY!

class App extends React.Component {

  constructor(props) {
  super(props)

  this.state = {
    color: '#FFF',
    color_white: true,
    currentWord: '',
    board1: [],
    row1: ["aaafrs","aaeeee","aafirs","adennn","aeeeem"],
  }

  this.clicked = this.clicked.bind(this);
}

componentWillMount() {
  let letter1 = '';

  this.state.row1.forEach(die => {
    letter1 = die[Math.floor(Math.random() * 6)].toUpperCase();
    if (letter1 === 'Q') {
      this.state.board1.push("Qu")
    } else {
      this.state.board1.push(letter1);
    }
  })
}

clicked(event) {
  //change background color
  let newColor= this.state.color === "#FFF" ? "#ACCEEC" : "#FFF";
  this.setState({ color: newColor });
  event.target.style.backgroundColor = newColor;
}

render () {
  return ( 
   <div id="board">
      <div className="row">
        {

          this.state.board1.map((letter, index) => {
          return (
            <div className="btn" onClick={(e) => {this.clicked(e)}}> 
              {letter}
            </div>
          )
        })}
      </div>
  ) 
}

1 个答案:

答案 0 :(得分:2)

问题是:

您正在为所有元素bg切换维护一个变量, 所以代码工作正常,

没有必要为此保持状态。

你能做的是:

像这样设置额外属性data-color

<div className="btn" data-color='#FFF' onClick={(e) => {this.clicked(e)}}>

根据attr改变bg颜色和data-color,onClick就像这样

clicked(event) {

    // get current color of element
    let currentColor = event.target.attributes['data-color'].value;

    // apply condition based upon currentColor
    let newColor = currentColor === "#FFF" ? "#ACCEEC" : "#FFF";

    // set the bg color 
    event.target.style.backgroundColor = newColor;

    // change the data-color value to currentColor
    event.target.setAttribute('data-color' , newColor);

    // add letter to state.currentWord
    let letter = event.target.innerText;
    this.setState({ currentWord: this.state.currentWord + letter })
}

以下是工作小提琴的链接:

https://jsfiddle.net/vivekdoshi2/kt2qgfpr/2/