N
N
Nikita2015-08-13 20:28:34
JavaScript
Nikita, 2015-08-13 20:28:34

How to properly forward events in react?

Hello. So I’m twisting react and in the process of studying the question arose, how is it more correct to forward events? At the moment, nothing smarter than the code below came to my mind ...

const MySuperInput = React.createClass({
  render: function () {
    const attr = { type: this.props.type };
    attr[this.props.eventName] = this.props.eventHandler;
    return React.createElement("input", attr);
  }
});

const MySuperComponent = React.createClass({
  _handle: function (e) {
    //какой-то обработчик
  },
  render: function () { 
    return <MySuperInput type="text" eventName="onChange" eventHandler={this._handle}/>
  }
});

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Andrey Antropov, 2015-08-14
@jetu

Like this:

class Input {
  render() {
    return <input {...props} />
  }
}

class MyComponent extends Component {
  constructor(props) {
    super(props);

    this.state = {};
  }

  handleChange = e => {
    this.setState({e.target.value});
  }

  render() {
    return <Input type="text" onChange={this.handleChange} value={this.state.value} />
  }
}

And I recommend reading about ValueLink https://facebook.github.io/react/docs/two-way-bind...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question