反应。指定只有一个Div的索引

时间:2016-10-24 22:29:13

标签: javascript css react-native

下面我有一个组件,似乎工作正常,但是当我点击其中一个div的所有div的变化。我似乎无法弄清楚是否需要添加key,ref或index元素。我试过这三个都无济于事。我认为ES6让我失望了。基本上,我希望只更改点击的div的颜色。

  import React from 'react';
    class AwesomeComponent2 extends React.Component {
      constructor(props){
        super(props);
        this.state = {
          onClicked: false
        }
        this.handlerButtonOnClick = this.handlerButtonOnClick.bind(this);
      }
      handlerButtonOnClick(event){
        alert(event.target);
        this.setState({
           onClicked: true
        });
      }
      render() {
        var _style;
        if (this.state.onClicked){ // clicked button style
          _style = {
              backgroundColor: "#FAE456"

            }

        }
        else{ // default button style
          _style = {
              backgroundColor: "#B3B3B3"
            }
        }
        return (
            <div className="main-container">
            <div onClick={this.handlerButtonOnClick}
                    style={_style} className ="nineBoxes"> </div>
            <div onClick={this.handlerButtonOnClick}
                    style={_style} className ="nineBoxes" className="nineBoxes"> </div>
            <div onClick={this.handlerButtonOnClick}
                    style={_style} className ="nineBoxes" className="nineBoxes"> </div>
          </div>
        );
      }
    }

以下链接并未向我说明此问题。

Getting Index of onClick target with ReactJs

1 个答案:

答案 0 :(得分:1)

您可以将参数传递给onClick函数。

<div onClick={() => this.handlerButtonOnClick('div1')}>

将该值保存在州:

handlerButtonOnClick(div) {
  this.setState({
    clickedDiv: div
  });
}

然后在render

中有条件地应用该样式
<div style={this.state.clickedDiv === 'div1' ? clickedStyle : defaultStyle}>

更新

假设您没有跟踪一个单击的项目,而是希望能够打开和关闭项目,基本上将它们切换到数组中。

您的onClick函数不需要更改,但处理程序逻辑可以:

handlerButtonOnClick(div) {
  let resultingArray = [];
  // check if the div is already in your state array
  if (this.state.clickedDivs.includes(div)) {
    // if it is, filter it out
    resultingArray = this.state.clickedDivs.filter(d => d !== div)
  } else {
    // if it isn't, concatenate your state array with the new div
    resultingArray = this.state.clickedDivs.concat(div)
  }

  this.setState({
    clickedDivs: resultingArray
  });
}

现在单击div将在单击状态中添加或删除自身,您可以检查它是否在数组中以应用样式。

<div style={this.state.clickedDivs.includes('div1') ? clickedStyle : defaultStyle}>

如评论中所述,如果您愿意,defaultStyle可以是空对象。