簡體   English   中英

通過地圖對多個元素進行反應

[英]React refs on multiple elements through map

當在外部單擊下拉菜單時,我有一個要捕獲的代碼可以正常工作:

renderTypes() {
    return _.map(this.props.items, (item, index) => {
        return (
                    <div className="ui icon top dropdown" tabIndex="0">
                        <div className={"menu transition" + classe} 
                             tabIndex="-1"
                             ref={node =>  this.node = node }/>
                    </div>
        );
    });
}

componentDidMount() {
    document.addEventListener('mousedown', this.handleClickOutside);
}

componentWillUnmount() {
    document.removeEventListener('mousedown', this.handleClickOutside);
}

handleClickOutside(e){
    const domNode = ReactDOM.findDOMNode(this.node);

    if(!domNode || !domNode.contains(e.target)){
        this.setState({open: ""});
    }
}

但實際上,這僅適用於最后一個下拉列表。 我很確定這是因為ref不能很好地分配給我的div,我想知道如何在地圖中使用它。

我的代碼正確還是我錯過了什么?

當您在ref={node => this.node = node }之類的映射中分配ref時,相同的ref被覆蓋,因此該ref僅保存最后一個節點的實例。 您應該改為在Dropdown項目周圍的包​​裝中添加ref

renderTypes() {
    return <div ref={node =>  this.node = node }>{_.map(this.props.items, (item, index) => {
        return (
                    <div className="ui icon top dropdown" tabIndex="0">
                        <div className={"menu transition" + classe} 
                             tabIndex="-1"
                         />
                    </div>
        );
    })}</div>;
}

暫無
暫無

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

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