在状态变化时对变更类名做出反应

gam*_*mer 35 javascript reactjs

我有一个这样的州,我正在设置activeclass标记这样:

constructor(props) {
        super(props);
        this.state = {'active': false, 'class': 'album'};
    }

  handleClick(id) {
    if(this.state.active){
      this.setState({'active': false,'class': 'album'})
    }else{
      this.setState({'active': true,'class': 'active'})
    }
  }
Run Code Online (Sandbox Code Playgroud)

我有一个州名列表项目列表:

<div className={this.state.class} key={data.id} onClick={this.handleClick.bind(this.data.id}>
    <p>{data.name}</p>
</div>
Run Code Online (Sandbox Code Playgroud)

在这里如何更改特定div的类名?

Jon*_*ell 59

下面是我认为你要做的事情的完整功能示例(使用功能代码段).

说明

根据您的问题,您似乎正在state为所有元素修改1个属性.这就是为什么当你点击一个时,所有这些都被改变了.

特别要注意,状态跟踪哪个元素处于活动状态的索引.当MyClickable被点击时,它告诉Container它的索引,Container更新state,随后isActive相应的财产MyClickable秒.

class Container extends React.Component {
  state = {
    activeIndex: null
  }

  handleClick = (index) => this.setState({ activeIndex: index })

  render() {
    return <div>
      <MyClickable name="a" index={0} isActive={ this.state.activeIndex===0 } onClick={ this.handleClick } />
      <MyClickable name="b" index={1} isActive={ this.state.activeIndex===1 } onClick={ this.handleClick }/>
      <MyClickable name="c" index={2} isActive={ this.state.activeIndex===2 } onClick={ this.handleClick }/>
    </div>
  }
}

class MyClickable extends React.Component {
  handleClick = () => this.props.onClick(this.props.index)
  
  render() {
    return <button
      type='button'
      className={
        this.props.isActive ? 'active' : 'album'
      }
      onClick={ this.handleClick }
    >
      <span>{ this.props.name }</span>
    </button>
  }
}

ReactDOM.render(<Container />, document.getElementById('app'))
Run Code Online (Sandbox Code Playgroud)
button {
  display: block;
  margin-bottom: 1em;
}

.album>span:after {
  content: ' (an album)';
}

.active {
  font-weight: bold;
}

.active>span:after {
  content: ' ACTIVE';
}
Run Code Online (Sandbox Code Playgroud)
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.6.1/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.6.1/react-dom.min.js"></script>
<div id="app"></div>
Run Code Online (Sandbox Code Playgroud)

更新:"循环"

在回应关于"循环"版本的评论时,我认为问题是关于渲染MyClickable元素数组.我们不会使用循环,而是映射,这在React + JSX中是典型的.以下应该给出与上面相同的结果,但它适用于一组元素.

// New render method for `Container`
render() {
  const clickables = [
    { name: "a" },
    { name: "b" },
    { name: "c" },
  ]

  return <div>
      { clickables.map(function(clickable, i) {
          return <MyClickable key={ clickable.name }
            name={ clickable.name }
            index={ i }
            isActive={ this.state.activeIndex === i }
            onClick={ this.handleClick }
          />
        } )
      }
  </div>
}
Run Code Online (Sandbox Code Playgroud)