【问题标题】:React TypeScript select node contents from a refReact TypeScript 从 ref 中选择节点内容
【发布时间】:2021-10-31 22:01:18
【问题描述】:

我是否有可能将 React ref 提供给文档范围 .selectNodeContents() 函数。我最终得到的错误是:

Argument of type 'HTMLDivElement | null' is not assignable to parameter of type 'Node'.
  Type 'null' is not assignable to type 'Node'.ts(2345)
(property) React.RefObject<HTMLDivElement>.current: HTMLDivElement | null

我的假设是 ref 是在实际分配之前声明的,但我真的不明白如何在 TypeScript 中克服这个问题。抱歉,如果重复,只是在互联网上没有找到它

export const Code: FC<ICode> = ({
    codeString
}) => {
    const codeRef = useRef<HTMLDivElement>(null);

    const clickHandler = (e: React.MouseEvent<HTMLDivElement>) => {
        let range = document.createRange();
        range.selectNodeContents(codeRef.current); // <-- Error here!!
        window.getSelection()?.removeAllRanges();
        window.getSelection()?.addRange(range);

        navigator?.clipboard?.writeText(codeString);
    };

    return (
        <div
          id="Code"
          className="Code"
          onClick={clickHandler}
          ref={codeRef}
        >
            { codeString }
        </div>
    );
}

【问题讨论】:

    标签: javascript reactjs typescript ref


    【解决方案1】:

    这是因为codeRef.current 可能是nullHTMLDivElement,而selectNodeContents 只期望Node

    您需要做的就是将codeRef.current 包装成条件:

    import React, { FC, useRef } from 'react'
    
    interface ICode {
      codeString: string
    }
    export const Code: FC<ICode> = ({
      codeString
    }) => {
      const codeRef = useRef<HTMLDivElement>(null);
    
      const clickHandler = (e: React.MouseEvent<HTMLDivElement>) => {
        let range = document.createRange();
        if (codeRef.current) {
          range.selectNodeContents(codeRef.current); // ok
          window.getSelection()?.removeAllRanges();
          window.getSelection()?.addRange(range);
    
          navigator?.clipboard?.writeText(codeString);
        }
      };
    
      return (
        <div
          id="Code"
          className="Code"
          onClick={clickHandler}
          ref={codeRef}
        >
          {codeString}
        </div>
      );
    }
    

    Playground

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-08-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多