问题
I am trying to implement select/unselect all functionality in reactJs but couldn't make it happen.
I have made select/unselect all main header checkbox functional and the single elements can also be selected or unselected.
My work link:
import React, { Component } from 'react'
import ReactDOM from 'react-dom'
class Box extends Component{
constructor(props){
super(props);
this.state = {
allChecked: false,
list: [
{id:1, name: "item1", isChecked: false},
{id:2, name: "item2", isChecked: false},
{id:3, name: "item3", isChecked: false},
],
};
}
handleChange = (e) => {
let list = this.state.list;
let allChecked = this.state.allChecked;
if(e.target.value === "checkAll"){
list.forEach(item => {
item.isChecked = e.target.checked;
allChecked = e.target.checked;
});
}
else{
list.find( item => item.name === e.target.name).isChecked = e.target.checked;
}
this.setState({list:list, allChecked: allChecked});
}
renderList = () => {
return this.state.list.map(item =>
<div>
<input key={item.id} type="checkbox" name={item.name} value={item.name} checked={item.isChecked} onChange={this.handleChange} />
<label>{item.name}</label>
</div>
)
}
render(){
return(
<div>
<input type="checkbox"
value="checkAll"
checked={this.state.allChecked}
onChange={this.handleChange} />Check all
<br/>
{this.renderList()}
</div>
);
}
}
ReactDOM.render(<Box/>, document.getElementById('root'));
To be straight forward, i want this (https://jsfiddle.net/52uny55w/) type of functionality using the plain Javascript but not with the jquery for some reasons.
回答1:
I have solved the problem at https://codesandbox.io/s/vvxpny4xq3
handleChange = e => {
let itemName = e.target.name;
let checked = e.target.checked;
this.setState(prevState => {
let { list, allChecked } = prevState;
if (itemName === "checkAll") {
allChecked = checked;
list = list.map(item => ({ ...item, isChecked: checked }));
} else {
list = list.map(item =>
item.name === itemName ? { ...item, isChecked: checked } : item
);
allChecked = list.every(item => item.isChecked);
}
return { list, allChecked };
});
};
A few things to note.
1) I have updated the checkAll button to have a name
property to ensure consistency
2) If modifying the existing state, use the new functional syntax
3) Destructure the objects and do not mutate them in place if possible. You could use map
instead of forEach and use spread operator to modify the object without mutating.
来源:https://stackoverflow.com/questions/54546096/select-unselect-all-checkbox-in-reactjs