簡體   English   中英

如何將多個事件偵聽器從React中的父組件附加到子組件的同一事件中?

[英]How do I attach multiple event listeners to the same event of a child component from its parent component in React?

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

編輯:父/子關系以及應該附加額外事件監聽器的方式/位置使得這個問題與我看到的其他問題略有不同,其中答案是將回調(或回調數組)傳遞給子組件。 我沒有權限更改子組件的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
};

到目前為止,我發現這樣做的最好方法是使用refs和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
};

暫無
暫無

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

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