2017-07-25 59 views
0

我正在学习react.js。反应:如何使用数据库?

如何正确添加class'use'到发生点击的元素?从其他元素,它需要被删除。

如何摆脱索引,但能够处理和处理的项目?

var DB = [ 

    { 
     name: 'Имя 1', url: 'http://localhost:1', use: true 
    }, 
    { 
     name: 'Имя 2', url: 'http://localhost:2', use: false 
    }, 
    { 
     name: 'Имя 3', url: 'http://localhost:3', use: false 
    } 
]; 

class SideBarEl extends React.Component { 
    hoverLi(t){ 
     if(t.target.id !== ''){ 
      for (var i = 0; i < DB.length; i++){ 
       if(t.target.id == i){ 
        DB[i].use = true; 
       } else { 
        DB[i].use = false; 
       } 
      } 
     } 
    } 
    render(){ 
     var newsTemplate = DB.map(function(item, index) { 
      return (
       <li key={ index } id={ index } onClick={ this.hoverLi.bind(this)} className={ item.use ? 'use' : '' }> 
        { item.name } 
        <span> 
         { item.url } 
        </span> 
       </li> 
      ) 
     }, this); 
     return(
      <ul>{newsTemplate}</ul> 
     ) 
    } 
} 

回答

0

1套this.state

您需要使用阵营state动作时出现来处理这样的事情,并重新呈现。如果你只是使用一个变量,React不知道什么时候应该重新渲染。

this.state = { 
    links: [ 
    { 
     name: "Имя 1", 
     url: "http://localhost:1", 
     use: true 
    }, 
    { 
     name: "Имя 2", 
     url: "http://localhost:2", 
     use: false 
    }, 
    { 
     name: "Имя 3", 
     url: "http://localhost:3", 
     use: false 
    } 
    ] 
}; 

了解更多关于国家对https://facebook.github.io/react/docs/state-and-lifecycle.html

2更新状态使用onClick

handleClick(item) { 
    this.setState(prevState => ({ 
    links: prevState.links.map(link => { 
     link.use = link === item; 
     return link; 
    }) 
    })); 
} 

render() { 
    // rest of code... 
    <li 
    key={item.url} 
    id={index} 
    onClick={() => this.handleClick(item)} 
    className={item.use ? "use" : ""} 
    > 
    // rest of code... 
} 

因为只有3个环节也没关系有这样的非优化的代码。如果您希望将此应用于大量链接(数百或数千个链接),则需要多一点工作,但可能超出了问题的范围。

3演示

https://codesandbox.io/s/mQoomVOmA

如果你点击一个链接,这将是红色,其余的将是黑色的,因为我加入这个小CSS .use { color: red; }

玩得开心和快乐编码。