2015-05-05 83 views
3

我在寫輸入元素的擴展版本。下面是它的一個簡化版本:與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); 
} 

但我很擔心,如果它是安全的。

+0

我想不出任何理由,它不會安全。我做了類似的事情,結果很好。 – Crob

回答

4

從這裏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); 
     } 
    } 
}); 
相關問題