2017-03-13 47 views
0

如何應用停留的類?我必須使用else語句來設置類爲null。如果我不提供else語句,我會得到一個錯誤。應用permenant類使用onMouseEnter中的反應

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> 
     ); 
    } 
} 
+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') 
);