简体   繁体   中英

How to handle event bubbling in Javascript

I implemented a toggle button for a list of items. To display the items and the toggle button, I run them through a loop given below.

renderRowValue = (values) => {
    const sourceId = values.id;
    const payload = {id: values.id, isActive: !values.isActive };
    return (
        <tr>
            <td key = {sourceId}>
                {values.name}
            </td>
            <td>
                <SwitchToggleButton
                    onChange={this.handleToggleChange(payload)}
                    defaultChecked={values.isActive}
                    label={"version2"}
                />
            </td>
        </tr>
    )
};

Then I call the function to display the value in the renderRowValue like this below:

<Grid xs={12} sm={12} md={10} className="shadow-border">
                <Row>
                    <Table striped bordered hover>
                        <thead>
                        <tr>
                            <th>Source</th>
                        </tr>
                        </thead>
                        <tbody>
                        {values.map(this.renderRowValue)}
                        </tbody>
                    </Table>
                </Row>
            </Grid>

But the main issue is that when I toggle a button on the value of the others changes.For example, I turn the first item on, then everything else turns on automatically, the same for when I turn it off.

The function to handle toggle switch can be found below:

handleToggleChange =(values) => {
    this.props.dispatch(values.isActive(values));
};

Please how can I fix this issue to just turn it on for the first item without affecting the rest?

assuming the handleToggleChange is in the same class as your component.

Update it so that it's a closure

handleToggleChange = (payload) = (e) => {
    e.preventDefault()
    this.props.dispatch(values.isActive(payload));
};


// renderRowValue 

<SwitchToggleButton
  onChange={this.handleToggleChange(payload)}
  defaultChecked={values.isActive}
  label={"version2"}
/>

This is how I've done it trying to stick as close to your code as possible without actually seeing all of your code.

https://gist.github.com/leslie-alldridge/5ffd25cfbd48c3134495b2245aa9d7ad

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM