简体   繁体   中英

How to use multiple ref variables on same html element in react?

Here is the brief snippet of my functional component's render method(removed unnecessary code for brevity)

  return (
    <Draggable draggableId={id} index={index}>
      {(provided, snapshot) => (
        <>
          <div className="carditem" ref={provided.innerRef} {...provided.draggableProps} {...provided.dragHandleProps} onClick={onClick}>
            <span className="carditem_title">{card.title}</span>
            <i className="fas fa-pencil-alt edit_button" onClick={onEditClick} />
            {hasDescription && <i className="fas fa-align-left desc_tag" title="This card has a description" />}
          </div>
          {isEditing && showOverlay && <input className="card_edit" type="text" autoFocus />}
        </>
      )}
    </Draggable>
  );

On line 5, if you notice I have a

ref={provided.innerRef}

I want to get the x,y coordinate of div with className="cardItem" and therefore I want to add a ref to that element. But a ref already exists as shown above. How can I add my own ref variable without breaking existing ref?

Not sure if it helps, but I am using react-beautiful-dnd and which is where that provided.innerRef comes from.

You can use the callback to bind multiple refs

const refHanlder = el => {
  refA.current = el;
  refB.current = el;
}

ref={el => refHandler}

The callback is also used for Array of refs

ref={el => elementRef.current[x] = el}

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