【问题标题】:React Event Bubbling: Finding the target ComponentReact 事件冒泡:寻找目标组件
【发布时间】:2017-07-03 16:01:38
【问题描述】:

我有一个 <ul> 组件包装了一些 <li> 组件。我想避免为每个li 添加一个onClick 处理程序,而是在ul 上使用一个处理程序并捕获冒泡事件。

从冒泡事件中确定/分配被点击组件的正确方法是什么?

class ListItemComponent extends React.Component {
    public render() {
        return (
            <li>Foo</li>
        )
    }
}

class ListComponent extends React.Component {
    private handleClick(event) {
        const target = event.target;
        // Determine clicked component, or index etc … ?
    }

    public render() {
        const items = this.props.items.map((x, i) => {
            <ListItemComponent active=“false” key={i} />    
        })
        return (
            <ul onClick={this.handleClick} />
                { items }
            </ul>
        )
    }   
}

【问题讨论】:

  • 你不能在 React 中传递event。将event.target 直接传递到您的handleClick 函数中。
  • 我不确定您建议的是什么解决方案。你能举个例子吗?在我给出的示例中,我当然可以访问该事件。
  • 我只是说,当你在周围传递事件时,你真的得到了 SyntheticEvent,这更难处理。

标签: javascript reactjs dom-events event-bubbling


【解决方案1】:

我的解决方案是为每个子组件添加一个data-index 属性,该属性可用于识别组件。

这避免了添加多个事件侦听器,同时也避免了多个ref 回调以获取子 DOM 元素的开销:

class ListItemComponent extends React.Component {
    public render() {
        return (
            <li data-index={this.props.index}>Foo</li>
        )
    }
}

class ListComponent extends React.Component {
    private handleClick(event) {
        const activeIndex = event.target.getAttribute('data-index');
        this.setState({ activeIndex });
    }

    public render() {
        const active = this.state.activeIndex;
        const items = this.props.items.map((x, i) => {
            <ListItemComponent active={i === active} key={i} index={i} />    
        })
        return (
            <ul onClick={this.handleClick} />
                { items }
            </ul>
        )
    }   
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-12-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-15
    • 2014-07-26
    • 1970-01-01
    相关资源
    最近更新 更多