[英]React refs on multiple elements through map
I have a code to catch when the dropdown is clicked outside which is working fine : 当在外部单击下拉菜单时,我有一个要捕获的代码可以正常工作:
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: ""});
}
}
But in fact this is working only on the last dropdown. 但实际上,这仅适用于最后一个下拉列表。 I'm pretty sure that this is because of ref which is not well given to my div and I would like to know how to use it with a map.
我很确定这是因为ref不能很好地分配给我的div,我想知道如何在地图中使用它。
Is my code correct or did I miss something? 我的代码正确还是我错过了什么?
When you assign ref within map like ref={node => this.node = node }
the same ref is being overridden and hence the ref
will only hold the instance of last node. 当您在
ref={node => this.node = node }
之类的映射中分配ref时,相同的ref被覆盖,因此该ref
仅保存最后一个节点的实例。 You should instead add a ref to the wrapper around Dropdown items 您应该改为在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.