[英]Add multiple functions / handlers for the same event on the same DOM element?
[英]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.