Binding Events Programmatically (SyntheticEvent)

I have a container with several blocks input

(with different properties). I would like to change the keydown behavior for all of them. I am wondering if there is a better way than to manually place the property onKeyDown={this.handleKeydown}

on each <input>

.

Since ReactJS has its own system SyntheticEvent

, I don't want to bind regular javascript events that might interfere with the ReactJS event system.

Is this possible with React?

+3


source to share


2 answers


Two options come to mind



  • You can use jsx spread object and attributes

    var props = {onKeyDown: this.handleKeyDown};
    return (
      <input {...props} name="foo" />
      <input {...props} name="bar" />
      <input {...props} name="qux" />
    );
    
          

  • You can create a custom component

    var MyInput = React.createClass({
      handleKeyDown: function() {
        // ...
      },
      render: function() {
        return (
          <input onKeyDown={this.handleKeyDown} />
        );
      }
    });
    
          

    Then use it like in another component

    render: function() {
      return (
        <MyInput name="foo" />
        <MyInput name="bar" />
        <MyInput name="qux" />
      );
    }
    
          

+1


source


An alternative is to put onKeyDown={this.handleKeydown}

on a component that contains all <input>

s, but its suitability depends on what else is in one container (other inputs and custom items).



0


source







All Articles