我在React中做一个计数器,并在onclick事件中执行以下操作:
我有以下代码:
import React , {Component} from "react";
import Counter from './counter';
class Counters extends Component{
state = {
counters : [
{id: 1 , value : 10 },
{id: 2 , value : 20 },
{id: 3 , value : 30 },
{id: 4 , value : 40 }
],
}
handleIncrement=(counter)=>{
var counters_temp = [...this.state.counters];
var counters_temp=counters_temp.map((c)=>{
c.id===counter.id?c.value++ : c;
return(c);
});
this.setState({counters : counters_temp});
}
render(){
return(
<div>
{this.state.counters.map((counter)=>
<Counter
onIncrement = {this.handleIncrement}
counter = {counter}
id = {counter.id}
>
</Counter>
)}
</div>
);
}
}
export default Counters;
handleIncrement函数给出以下错误。
“预期了一个赋值或函数调用,而是看到了一个表达式”。如果我在javascript文件中编写独立的samehandleIncrement代码,则效果很好。
此外,如果注释掉:c.id===counter.id?c.value++ : c;
并写:
handleIncrement=(counter)=>{
var counters_temp = [...this.state.counters];
var counters_temp=counters_temp.map((c)=>{
//c.id===counter.id?c.value++ : c;
return(c);
});
this.setState({counters : counters_temp});
}
然后没有编译错误,但也无法解决我的目的。 子组件计数器如下所示:
import React , {Component} from "react";
class Counter extends Component{
render(){
return(
<div>
<span class="badge badge-warning">{"Zero"}</span>
<button onClick = {()=>this.props.onIncrement(this.props.counter)} type="button" class="btn btn-secondary">Increment</button>
</div>
);
}
}
export default Counter;
为什么会这样?
答案 0 :(得分:0)
尝试一下
handleIncrement(counter){
var counters_temp = [...this.state.counters];
counters_temp=counters_temp.map((c)=>{
c.value = (c.id === counter.id) ?
c.value+1 : c.value;
return (c);
});
this.setState({counters : counters_temp});
}
检查工作,例如 https://jsfiddle.net/0ym96hx1/
答案 1 :(得分:0)
您的this.state.counters中没有任何“ id”作为属性。我认为您应该使用
c.key === counter.key
还显示计数器组件。它通过ID吗?