使用 Reactjs 为同一事件和元素提供多个事件处理程序

2024-04-06

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

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根据属性的顺序覆盖另一个。

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

Edit


I was able to swap onChange and {...this.props} in the component and use
changeHandler: function(event)
{
        console.log('input_changeHandler change');
        this.props.onChange(event);
}

但我担心它是否安全。


从这里的文档https://facebook.github.io/react/docs/jsx-spread.html 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);
        }
    }
});
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

使用 Reactjs 为同一事件和元素提供多个事件处理程序 的相关文章

随机推荐