Reactjs 对同一事件和元素的多个事件处理程序

Multiple event handlers for the same event and element with Reactjs

我正在编写输入元素的扩展版本。这是它的简化版本:

var MyInput = React.createClass({
    render: function () {
        return (
            <div>
                <input type="text" onChange={this.changeHandler} {...this.props} />
            </div>
        );
    },

    changeHandler: function(event){
        console.log('Trigger me first');
    }
});

我在这样的环境中使用它:

<MyInput placeholder="Test" value={this.state.myValue} onChange={function(event){
    console.log('Trigger me second');
}} />

正如您可能怀疑的那样 onChange 根据属性的顺序覆盖另一个。

考虑到这一点,您认为在这种情况下,为同一事件、同一元素实现对多个事件处理程序的支持的最简洁方法是什么?

编辑


我能够在组件中交换 onChange{...this.props} 并使用

changeHandler: function(event)
{
        console.log('input_changeHandler change');
        this.props.onChange(event);
}

但我担心它是否安全。

来自此处的文档 https://facebook.github.io/react/docs/jsx-spread.html

The specification order is important. Later attributes override previous ones.

因此,如果您将 onChange 放在传播之后,它将始终优先。然后您可以调用从您自己的处理程序传入的 onChange 函数。

var MyInput = React.createClass({
    render: function () {
        return (
            <div>
                <input type="text" {...this.props} onChange={this.changeHandler} />
            </div>
        );
    },

    changeHandler: function(event){
        console.log('Trigger me first');
        if (typeof this.props.onChange === 'function') {
            this.props.onChange(event);
        }
    }
});