我想练习Reactive18,一开始我收到了反对警告,我已经使用createRoot进行了更改。现在我面临一个错误
TS2345:类型为'HTMLElement收空‘的参数不能分配给类型’HTMLElement DocumentFragment‘的参数。类型'null‘不能分配到键入’元素\ DocumentFragment‘。
import React from "react";
import ReactDOM from "react-dom/client";
import "./index.css";
import App from "./App";
import reportWebVitals from "./reportWebVitals";
const root = ReactDOM.createRoot(document.getElementById("root")); // error: Type 'null' is not assignable to type 'Element | DocumentFragment'
root.render(
<React.StrictMode>
<App />
</React.StrictMode>
);
reportWebVitals();发布于 2022-04-09 12:51:46
这里的问题是,document.getElementById方法的返回类型是HTMLElement \ null。但是,另一方面,createRoot方法的预期参数类型是Element 000-DocumentFragment,因此提供的参数类型与预期的参数类型之间存在不匹配。
正确的方法是给出元素的类型定义或使用!。
const root = ReactDOM.createRoot(document.getElementById("root") as Element); 或
const root = ReactDOM.createRoot(document.getElementById("root")!);https://stackoverflow.com/questions/71808102
复制相似问题