[英]How to use multiple ref variables on same html element in react?
這是我的功能組件的渲染方法的簡短片段(為簡潔起見,刪除了不必要的代碼)
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>
);
在第 5 行,如果你注意到我有一個
ref={provided.innerRef}
我想用className="cardItem"
獲取div
的 x,y 坐標,因此我想為該元素添加一個引用。 但是 ref 已經存在,如上所示。 如何在不破壞現有 ref 的情況下添加自己的 ref 變量?
不確定它是否有幫助,但我正在使用 react-beautiful-dnd ,這就是provided.innerRef
的來源。
您可以使用回調綁定多個引用
const refHanlder = el => {
refA.current = el;
refB.current = el;
}
ref={el => refHandler}
回調也用於 Array of refs
ref={el => elementRef.current[x] = el}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.