【问题标题】:How do I attach multiple event listeners to the same event of a child component from its parent component in React?如何在 React 中将多个事件侦听器附加到来自其父组件的子组件的同一事件?
【发布时间】:2017-07-10 07:30:02
【问题描述】:

我正在创建一个接收链接、按钮或其他 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
};

【问题讨论】:

标签: javascript reactjs


【解决方案1】:

到目前为止,我发现的最佳方法是使用 refs 和 findDOMNode,正如上面 cmets 中所建议的那样。一旦有了对子组件的 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
};

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-29
    • 1970-01-01
    • 1970-01-01
    • 2018-03-24
    • 1970-01-01
    相关资源
    最近更新 更多