Javascript 反应:如何使用数据库?
我正在学习react.js 如何将类“use”正确添加到发生单击的元素中?需要从其他元素中删除它 如何摆脱索引,但能够处理和处置项目Javascript 反应:如何使用数据库?,javascript,reactjs,onclick,Javascript,Reactjs,Onclick,我正在学习react.js 如何将类“use”正确添加到发生单击的元素中?需要从其他元素中删除它 如何摆脱索引,但能够处理和处置项目 var DB = [ { name: 'Имя 1', url: 'http://localhost:1', use: true }, { name: 'Имя 2', url: 'http://localhost:2', use: false }, { name: 'Имя
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>
)
}
}
var DB=[
{
名称:“imk 1”,url:'http://localhost:1,使用:true
},
{
名称:“imk 2”,url:'http://localhost:2,使用:false
},
{
名称:“imk 3”,url:'http://localhost:3,使用:false
}
];
类SideBarEl扩展了React.Component{
霍维利(t){
如果(t.target.id!=''){
对于(var i=0;i
{item.name}
{item.url}
)
},这个);
返回(
{newsTemplate}
)
}
}
1套this.state
您需要使用Reactstate
来处理这些事情,并在操作发生时重新启动。如果你只是使用一个变量,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
}
]
};
了解更多关于州政府的信息
2使用onClick
handleClick(项目){
this.setState(prevState=>({
links:prevState.links.map(link=>{
link.use=链接===项目;
返回链接;
})
}));
}
render(){
//代码的其余部分。。。
this.handleClick(项)}
className={item.use?“use”:“}
>
//代码的其余部分。。。
}
只有3个链接可以有这样的非优化代码。如果您想将此应用于大量链接(数百或数千个链接),则需要做更多的工作,但可能超出您的问题范围
3演示
如果你点击一个链接,它将是红色的,其余的将是黑色的,因为我添加了这个小CSS。使用{color:red;}
有乐趣和快乐的编码
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...
}