簡體   English   中英

具有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);
        }
    }
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM