试用React 18 RC与TypeScript

217 阅读1分钟

React 18的候选版本刚刚发布了!我们可以通过TypeScript和创建React应用程序来尝试。

下面是我们如何用TypeScript和Create React App进行尝试。

首先,像往常一样,使用Create React App创建一个应用程序:

npx create-react-app app --template typescript

然后更新React的版本:

npm install react@rc react-dom@rc --force

--force 标志可以解决目前与React测试库的依赖问题。

  • index.tsx ,替换以下几行:
ReactDOM.render(
  <React.StrictMode>
    <App />
  </React.StrictMode>,
  document.getElementById('root')
);

与:

const root = ReactDOM.createRoot(
  document.getElementById("root") as HTMLDivElement
);
root.render(<App />);

这将产生类型错误:

Property 'createRoot' does not exist on type 'typeof import("/...")'

...这可以通过在tsconfig.json 中添加以下内容来解决:

{
  "compilerOptions": {
    ...,
    "types": ["react/next", "react-dom/next"]  },
  ...
}

就这样,你现在可以开始玩React 18了! 😊