2017-02-20 25 views
1

我創建了一個接收鏈接,按鈕或其他React組件(子級)作爲屬性的React組件(父級),並且我想將附加的單擊處理程序附加到傳入的組件。這個子組件通常已經定義了一個點擊處理程序,所以我不能只使用React.cloneElement將onClick添加到它。另外,有時子組件的click處理程序會阻止事件傳播到父組件,所以我不能只將click監聽器附加到父級,並允許事件冒泡。如何在React中將多個事件偵聽器附加到其父組件的同一事件?

編輯:父/子關係以及附加事件偵聽器應如何連接使得此問題與我見過的其他問題略有不同,答案是傳遞迴調(或回調數組) )到子組件中。我無權修改子組件的API。

下面是一些示例代碼:

export default class ParentComponent extends React.Component { 
    constructor(props) { 
     super(); 

     this.handleClick = this.handleClick.bind(this); 
    } 

    handleClick(event) { 
     // do something (this is not working) 
    } 

    render() { 
     let { childComponent } = this.props; 

     return (
      <div> 
       {React.cloneElement(childComponent, { 
        onClick: this.handleClick 
       })} 
      </div> 
     ) 
    } 
} 

ParentComponent.PropTypes = { 
    childComponent: PropTypes.element 
}; 
+1

的可能的複製[如何React.js多個事件處理程序添加到同一事件] (http://stackoverflow.com/questions/33398613/how-to-add-multiple-event-handlers-to-same-event-in-react-js) – djthoms

+1

你有沒有試過[refs](https:// facebook .github.io/react/docs/refs-and-the-dom.html)或[findDomNode](https://facebook.github.io/react/docs/react-dom.html#finddomnode)? –

+0

謝謝@TelmanAgababov!對於React我很新,你的建議運行良好。如果您需要信用,請隨時發佈代碼示例作爲答案,我會接受它。 – Jared

回答

0

我發現要做到這一點,最好的辦法至今使用裁判和findDOMNode,上面的意見建議。一旦你有了孩子組件的DOM節點的引用,您可以添加當父組件被安裝在一個普通事件偵聽器:

export default class ParentComponent extends React.Component { 
    constructor(props) { 
     super(props); 
    } 

    componentDidMount() { 
     this.childComponentRef.addEventListener('click', function() { 
      // do something (this works!) 
     }, false); 
    } 

    render() { 
     let { childComponent } = this.props; 

     return (
      <div> 
       {React.cloneElement(childComponent, { 
        ref: (childComponentRef) => { 
         this.childComponentRef = ReactDOM.findDOMNode(childComponentRef); 
        } 
       })} 
      </div> 
     ) 
    } 
} 

ParentComponent.PropTypes = { 
    childComponent: PropTypes.element 
}; 
相關問題