使用react更改列表中的活动元素

rks*_*ksh 6 javascript css jquery reactjs

我有一个通过在react上使用数组创建的元素列表.在用户单击时,如何使单击的元素处于活动状态(通过添加css类),同时使其他元素为inative(通过删除活动类)?

我对elemetns的渲染看起来像这样.

   {this.props.people.map(function(person, i){
        <div className='media' key={i} onClick={state.handleClick.bind(state,i,state.props)}>
          <item className="media-body">{person.name}</item>
        </div>
    }
Run Code Online (Sandbox Code Playgroud)

在用户单击其中一个元素时,活动类将添加到单击的"media"元素中,使得单击元素"media active",同时从之前单击的元素中删除"active"类?

Yad*_*ran 12

  constructor(props) {
    super(props);
    this.state = { activeIndex: 0 };
  }

  handleClick(index, props) {
    // do something with props
    // ...    

    // now update activeIndex
    this.setState({ activeIndex: index });
  }

  render() {
    return (
      <div>
        {
          this.props.people.map(function(person, index) {
            const className = this.state.activeIndex === index ? 'media active' : 'media';  
            return (
              <div className={className} key={index} onClick={handleClick.bind(this, index, this.props)}>
                <item className="media-body">{person.name}</item>
              </div>
            );
          }, this)
        }
      </div>
    );
  }
Run Code Online (Sandbox Code Playgroud)