动态更改多个组件的更改状态

时间:2016-11-10 14:28:39

标签: javascript reactjs

我遇到了React Component的问题。我有这个

class SidebarItem extends React.Component{
constructor(props) {
    super(props)
    this.state = { isActive: false }
}
handleClick() {
    var active = !this.state.isActive;
    this.setState({ isActive: active });
}
render() {
    var className = 'item';
    if(this.state.isActive){className = 'active item'} else {className = 'item'};
    return (
        <Link className={className} to={this.props.href} onClick={this.handleClick.bind(this)}>
            {this.props.label}
        </Link>
    );
}
}


export class Sidebar extends React.Component {
constructor(props) {
    super(props)
}
render() {
    var elements = this.props.defaults.elements.map(function (i) {
        return (
            <SidebarItem label={i.label} href={i.href} key={i.label} />
        );
    });
    return (
            <div className={this.props.defaults.class}>
                {elements}
            </div>
    );
}
};

我的目标是为菜单的活动元素更改className。我无法理解,我必须如何翻译所有元素以清除活动状态并仅对一个单击的元素激活?

1 个答案:

答案 0 :(得分:2)

我认为你正在寻找像这样的东西

class Menu extends React.Component {
  constructor(){
    super()
    this.state = {
      items: ['Hello', 'world', 'it', 'is', 'me'],
      active: 0
    }
  }
  click(index){
    this.setState({active: index})
  }
  render(){
    const list = this.state.items.map((item,index) => {
      return <Item key={index} 
        className={this.state.active === index ? 'active' : ''} 
        text={item}
        click={this.click.bind(this, index)}
      />
    })
    return <ul>
        {list}
    </ul>
  }
}

class Item extends React.Component {
  render(){
    return <li onClick={this.props.click} 
             className={this.props.className}>
             {this.props.text}
           </li>        
  }
}


React.render(<Menu />, document.getElementById('container'));

希望它能帮到你fiddle