【发布时间】: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