我在<Panel value="room01">
中有一个房间名称列表。单击时,我需要将值(在属性中)保存到数组并将颜色更改为绿色。另一方面,我还需要能够撤消选择,这意味着需要从数组中删除该值,并且颜色必须恢复为默认值。如何在JS / React中实现呢?
使用以下功能,我可以将值获取到元素
onSelectRooms = (e) => {
const selectedRooms = e.target.getAttribute("value");
}
export default class ExportReportRoomSelectionModal extends React.Component {
constructor(props) {
super(props);
this.state = {
rooms: roomOrder,
selectedRooms: [],
};
this.onSelectRooms = this.onSelectRoom.bind(this);
}
onSelectRooms = (e) => {
const selectedRooms = e.target.getAttribute("value");
}
render() {
return (
<Modal>
<Modal.Header closeButton>
<Modal.Title>TItle</Modal.Title>
</Modal.Header>
<Modal.Body>
<p>Number of rooms: {this.state.rooms.length}</p>
<p>Rooms:</p>
<Grid fluid={true}>
<Row className="show-grid">
{ this.state.rooms.map((name, i ) =>
<Col key={i} xs={2} md={2}>
<Panel onClick={this.onSelectRooms}>
<Panel.Heading value={name}>
{name}
</Panel.Heading>
</Panel>
</Col>
)}
</Row>
</Grid>
</Modal.Body>
</Modal>);
}
}```
答案 0 :(得分:0)
<Panel onClick={this.handleClick.bind(this, name)}>
handleClick(name, e) {
if (this.state.selectedRooms.includes(name)) {
// remove from array
const newSelectedRooms = this.state.selectedRooms.filter(e => e !=== name);
this.setState({selectedRooms: newSelectedRooms}):
} else {
// add to array
this.setState(prevState => {selectedRooms: [..prevState.selectedRooms, name]});
}
<Panel
onClick={this.handleClick.bind(this, name)}
className={this.state.selectedRooms.includes[name] ? 'green' : ''}
>