Add event handler to React.DOM element dynamically

前端 未结 4 548
无人及你
无人及你 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:27

    To get an api like this (similar to ), we need to use the cloneWithProps addon.

      
        
        
        
      
    

    All this does is take each child, add a click handler, and conditionally add a className of 'active' to it. You easily can (and should) modify it to take the active class name as a prop.

    var RadioButtonGroup = React.createClass({
      render: function(){
        return 
    {React.Children.map(this.props.children, this.renderItem)}
    }, renderItem: function(button, index){ return React.cloneElement(button, { className: this.props.value === index ? ' active ' : '', onClick: function(){ this.props.onChange(index); }.bind(this), key: index }); } });

    demo

    If you don't want to use cloneWithProps, you could use a wrapper div, but styling may be a bit more complex.

      renderItem: function(button, index){
        return React.createElement('div', {
          className: this.props.value === index ? ' active ' : '',
          onClick: function(){ 
            this.props.onChange(index); 
          }.bind(this),
          key: index
        }, button);
      }
    

    The reason everything uses index is because you're passing react elements, which are opaque. There's no clean way to get any data out of these buttons, but we do know their index because we're iterating over them using React.Children.map. An alternative api would look like this:

    Test 1,
       test2: ,
       test3: 
    }} />
    

    Here we can iterate over this.props.options, and pass the key to the onChange callback, and take e.g. 'test1' as a value prop.

提交回复
热议问题