简体   繁体   English

如何在反应中在同一个 html 元素上使用多个 ref 变量?

[英]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在第 5 行,如果你注意到我有一个

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.我想用className="cardItem"获取div的 x,y 坐标,因此我想为该元素添加一个引用。 But a ref already exists as shown above.但是 ref 已经存在,如上所示。 How can I add my own ref variable without breaking existing ref?如何在不破坏现有 ref 的情况下添加自己的 ref 变量?

Not sure if it helps, but I am using react-beautiful-dnd and which is where that provided.innerRef comes from.不确定它是否有帮助,但我正在使用 react-beautiful-dnd ,这就是provided.innerRef的来源。

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回调也用于 Array of refs

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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