Add event handler to React.DOM element dynamically

前端 未结 4 630
无人及你
无人及你 2021-02-01 06:54

I\'m working with a RadioButtonGroup component which is like radio input but with buttons:

\"enter

4条回答
  •  感动是毒
    2021-02-01 07:49

    You don't want to mess with click handlers on each button, just listen for the click on the container. Then update the state based on which child is clicked.

    Also, with React it's best to keep all of your DOM stuff in the render function. In this case, defining an element's class name.

    Here's how this could work:

    var RadioButtonGroup = React.createClass({
        getInitialState: function getInitialState() {
            return {
                active: this.props.active || 0
            };
        },
    
        clickHandler: function clickHandler(e) {
            // Getting an array of DOM elements
            // Then finding which element was clicked
            var nodes = Array.prototype.slice.call( e.currentTarget.children );
            var index = nodes.indexOf( e.target );
            this.setState({ active: index });
        },
    
        render: function render() {
            var buttons = this.children.map(function(child, i) {
                if (i === this.state.active) child.props.className += ' active';
                return child;
            }, this);
    
            return (
                
    { buttons }
    ) } });

提交回复
热议问题