单击元素时需要更改颜色,同时将元素值保存在数组中

时间:2019-06-26 17:01:46

标签: javascript arrays reactjs event-handling

我在<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>);
    }
}```

1 个答案:

答案 0 :(得分:0)

  1. 使用名称道具而不是从事件处理程序中获取值是一种更好的方法。
    <Panel onClick={this.handleClick.bind(this, name)}>  
  1. handleClick逻辑,切换面板
    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]});
        }
  1. 如果要动态更改颜色,则应根据状态进行更改。假设您具有将颜色更改为绿色的类名。
    <Panel
        onClick={this.handleClick.bind(this, name)}
        className={this.state.selectedRooms.includes[name] ? 'green' : ''}
    >