javascript - React: how to work with the database? -
i'm studying react.js.
how correctly add class 'use' element click occurs? other elements needs removed.
how rid of index, able handle , dispose of items?
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 !== ''){ (var = 0; < 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> ) } }
1 set this.state
you need use react state
handle such things , rerender when action occurs. if use variable, react doesn't know when should rerendered.
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 } ] };
read more state on https://facebook.github.io/react/docs/state-and-lifecycle.html
2 update state using 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... }
for 3 links it's okay have such non-optimized code. if apply big collection of links (hundreds or thousands of links), require bit more work it's out of question's scope.
3 demo
https://codesandbox.io/s/mqoomvoma
if click on link, red , rest black because added small css .use { color: red; }
have fun , happy coding.
Comments
Post a Comment