在反应中使用onMouseEnter应用permenant类

时间:2017-03-13 05:50:48

标签: javascript reactjs

如何申请入学课程?我必须使用else语句将类设置为null。如果我不提供else语句,我将收到错误。

https://fiddle.jshell.net/8wsr7xa1

class App extends React.Component {
    constructor(props){
        super(props)

        this.state = {
            active: null
        }
    }

  onMouseEnter(item){
    this.setState({active: item})
  }

    render(){
        const items = [1,2,3,4,5];
        return (
            <div>
                {items.map((obj,i) =>  
                    <div 
                    key={i} 
                    style={this.state.active === obj ? 
                    {backgroundColor: 'yellow'} : {}} 
                    onClick={this.onMouseEnter.bind(this, obj)}>
                    {obj}
                    </div>
                 )}
            </div>
        );
    }
}

1 个答案:

答案 0 :(得分:0)

很难理解你的问题,但我认为这是你想要做的事情?

  

https://fiddle.jshell.net/8wsr7xa1/6/

class App extends React.Component {
  constructor(props){
      super(props)

      this.state = {
          actives: []
      }
  }

  onMouseEnter(item){
    let actives = [].concat(this.state.actives);
    if (actives.indexOf(item) === -1) { actives.push(item) }
    this.setState({actives});
  }

  render(){
      const items = [1,2,3,4,5];
      return (
          <div>
              {items.map((obj,i) =>  
                <div 
                  key={i} 
                  style={this.state.actives.indexOf(obj) > -1 ? 
                  {backgroundColor: 'yellow'} : {}} 
                  onMouseEnter={this.onMouseEnter.bind(this, obj)}>
                  {obj}
                  </div>
               )}
          </div>
      );
  }
}

React.render(
<App name="World"/ >,
document.getElementById('app')
);