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

Cha*_*vov 3 javascript 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');
    }
});
Run Code Online (Sandbox Code Playgroud)

我在这样的上下文中使用它:

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

您可能会怀疑onChange,根据属性的顺序,其中一个会覆盖另一个。

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

编辑


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

changeHandler: function(event)
{
        console.log('input_changeHandler change');
        this.props.onChange(event);
}
Run Code Online (Sandbox Code Playgroud)

但是我担心它是否安全。

Cro*_*rob 5

从这里的文档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);
        }
    }
});
Run Code Online (Sandbox Code Playgroud)