简体   繁体   English

如何设置从回调 ref 获得的元素的样式?

[英]How do you set the style of an element obtained from a callback ref?

My react library obtains a ref by giving the client a callback ref function to put on the element that the library is to operate on:我的 react 库通过给客户端一个回调 ref 函数来获取一个 ref ,以放置该库要操作的元素:

Conceptually:从概念上讲:

// --- library

export registerTarget = () => {
   return (targetRef) => {
      if (targetRef) {
         targetRef.style = {color: "red"};  // or more funky library stuff.
      }
   }
} 

// --- component

const targetMe = library.registerTarget('my-element');

return (
   <div ref={targetMe}>This is my element for the library to operate on</div>
);

I've read that when you make the ref using createRef, then it's type is React.RefObject<T> , but when you get the ref using a ref callback, you get the actual element.我已经读到,当您使用 createRef 创建 ref 时,它的类型是React.RefObject<T> ,但是当您使用 ref 回调获取 ref 时,您会得到实际的元素。

The problem is that you are allowed to assign to ref.current.style when ref is a React.RefObject<T> , but you are not allowed to assign to ref.style when ref is the thing that you got from a ref callback.问题是,当refReact.RefObject<T>时,您可以分配给ref.current.style ,但是当 ref 是您从 ref 回调中获得的东西时,您不能分配给 ref.style 。

Or at least, I can't work out how to type the thing that I get from a ref-callback: I've tried HTMLElement , but the error is that ref.style is read-only in that case.或者至少,我不知道如何键入从 ref-callback 获得的内容:我尝试过HTMLElement ,但错误是ref.style在这种情况下是只读的。

Like you said, you can't mutate ref.style since it's read-only however you can change the css properties inline-y:就像你说的,你不能改变ref.style因为它是只读的,但是你可以改变 css 属性 inline-y:

const registerTarget = () => {
  return (targetRef: HTMLElement | null) => {
    if (targetRef) {
      targetRef.style.color = "red"; // or more funky library stuff.
    }
  };
};

CodeSandbox Demo. CodeSandbox 演示。

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

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