简体   繁体   中英

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.

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. You should instead add a ref to the wrapper around Dropdown items

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>;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM