js-*_*ner 1 javascript arrays onchange reactjs
使用复选框 onChange 事件,如何在未选中反应时从状态数组中删除值?
状态数组:
this.state = { value: [] }
Run Code Online (Sandbox Code Playgroud)
onChange 函数:
handleChange = event => {
if (event.target.checked) {
this.setState({
value: [...this.state.value, event.target.value]
});
} else {
this.setState({
value: [this.state.value.filter(element => element !== event.target.value)]
});
}
};
Run Code Online (Sandbox Code Playgroud)
不确定 .filter() 到底应该做什么
你非常接近,除了:
您需要删除[]您对filter. filter返回一个数组。如果将其包装在 中[],则将数组放入另一个数组中,这是您不想要的(在这种情况下)。
和
由于您是根据现有状态更新状态,因此使用 的回调版本很重要setState,而不是直接接受对象的版本。状态更新可以一起批处理,因此您需要确保处理的是最新版本的数组。
所以:
handleChange = ({target: {checked, value: checkValue}}) => {
// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
// ^? destructuring to take the properties from the event,
// since the event object will get reused and we're doing
// something asynchronous below
if (checked) {
this.setState(({value}) => ({value: [...value, checkValue]}));
} else {
this.setState(({value}) => ({value: value.filter(e => e !== checkValue)}));
// ^??????????????????????????????????^??? No [] around this
}
};
Run Code Online (Sandbox Code Playgroud)
在某些情况下,您可以避免使用this.state.value而不是使用回调(例如,如果您只更新value以响应某些事件),但您必须确保您知道它们是哪些;使用回调更简单。
FWIW,因为它有多个值,如果是我,我会调用 state 属性values(复数)而不是value,这也意味着我们不必value在上面的解构中从事件目标中重命名:
handleChange = ({target: {checked, value}}) => {
if (checked) {
this.setState(({values}) => ({values: [...values, value]}));
} else {
this.setState(({values}) => ({values: values.filter(e => e !== value)}));
}
};
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
532 次 |
| 最近记录: |