【发布时间】:2020-02-17 21:37:59
【问题描述】:
我想更新 Counter 组件以采用 onIncrement 和 onDecrement 回调作为道具并确保它们更新计数器的值 独立。
每个回调只能接受一个整数作为参数 它告诉数量增加计数器的现有值。
我认为最好的方法是访问 Counter 组件的 'key' 属性?
沙盒:https://codesandbox.io/s/silly-sound-5ofef?from-embed 应用.js
import Counter from './components/Counter'
import './App.css'
export class App extends Component {
constructor(props, context) {
super(props, context)
this.state = {
data: [
{ id: 1, value: 0 },
{ id: 2, value: 0 },
{ id: 3, value: 0 },
{ id: 4, value: 0 },
],
}
}
onDecrement = e => {
this.setState(state => {
const data = state.data.map(item => {
return { id: item.id, value: (item.value -= e) }
})
return {
data,
}
})
}
onIncrement = e => {
this.setState(state => {
const data = state.data.map(item => {
return { id: item.id, value: (item.value += e) }
})
return {
data,
}
})
}
render() {
return (
<div>
{this.state['data'].map(counter => (
<Counter
key={counter.id}
value={counter.value}
onIncrement={this.onIncrement}
onDecrement={this.onDecrement}
/>
))}
</div>
)
}
}
export default App
Counter.js
export class Counter extends Component {
render() {
const { value, onIncrement, onDecrement } = this.props
return (
<div className="counter test">
<b>{value}</b>
<div className="counter-controls">
<button
className="button btn-danger btn-sm"
onClick={() => onDecrement(1)}
>
-
</button>
<button
className="button btn-success btn-sm"
onClick={() => onIncrement(1)}
>
+
</button>
</div>
</div>
)
}
}
export default Counter
【问题讨论】:
-
您也可以将点击元素的 ID 传递给
onIncrement(),然后您将找到该特定对象并设置其值 -
忘了说,onIncrement() 只能有一个参数,它必须定义我想增加计数器的数量。
-
你可以为
increment/decrement添加另一个prop,你可以称它为step,然后在你的Counter组件中使用它 -
我不能,我希望它那么容易。这是我必须完成的任务。
-
您是否正在递增和递减
data数组中的唯一项,因为我意识到根据您编写的这个组件,增量会将更改应用于数组中的所有项
标签: javascript reactjs