react 在table 表格外添加一个复选框 实现全选或取消全选
时间: 2023-11-27 19:52:43 浏览: 271
可以通过以下步骤在 React 中实现在表格外添加一个复选框并实现全选或取消全选功能:
1. 在表格外部添加一个复选框,并为其编写状态处理函数。
```jsx
class Table extends React.Component {
constructor(props) {
super(props);
this.state = {
isChecked: false
};
}
handleCheckAll = e => {
this.setState({
isChecked: e.target.checked
});
};
render() {
return (
<div>
<input type="checkbox" checked={this.state.isChecked} onChange={this.handleCheckAll} />
<table>
{/* ... */}
</table>
</div>
);
}
}
```
2. 在表格行中添加一个复选框,并在其上绑定一个 `checked` 属性,该属性值应该与外部复选框的状态保持一致。
```jsx
class Table extends React.Component {
constructor(props) {
super(props);
this.state = {
isChecked: false,
rows: [
{ id: 1, name: 'Alice', isChecked: false },
{ id: 2, name: 'Bob', isChecked: false },
{ id: 3, name: 'Charlie', isChecked: false }
]
};
}
handleCheckAll = e => {
const isChecked = e.target.checked;
const rows = this.state.rows.map(row => ({ ...row, isChecked }));
this.setState({
isChecked,
rows
});
};
handleCheckRow = (id, isChecked) => {
const rows = this.state.rows.map(row => row.id === id ? { ...row, isChecked } : row);
const isCheckedAll = rows.every(row => row.isChecked);
this.setState({
isChecked: isCheckedAll,
rows
});
};
render() {
return (
<div>
<input type="checkbox" checked={this.state.isChecked} onChange={this.handleCheckAll} />
<table>
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Is Checked</th>
</tr>
</thead>
<tbody>
{this.state.rows.map(row => (
<tr key={row.id}>
<td>{row.id}</td>
<td>{row.name}</td>
<td>
<input type="checkbox" checked={row.isChecked} onChange={e => this.handleCheckRow(row.id, e.target.checked)} />
</td>
</tr>
))}
</tbody>
</table>
</div>
);
}
}
```
3. 当外部复选框的状态发生改变时,需要更新表格行的复选框状态;当表格行的复选框状态发生改变时,需要更新外部复选框的状态。
上述代码中已经实现了这些功能,因此整个应用已经可以正常工作了。
阅读全文
相关推荐















