我正在通过从 YouTube 学习来尝试为我的项目使用 ChakraUI(使用 React、Vite 和 TypeScript)。我使用的是3.0.2版本。
{
"name": "client",
"private": true,
"version": "0.0.0",
"type": "module",
"scripts": {
"dev": "vite",
"build": "tsc -b && vite build",
"lint": "eslint .",
"preview": "vite preview"
},
"dependencies": {
"@chakra-ui/react": "^3.0.2",
"@emotion/react": "^11.13.3",
"@emotion/styled": "^11.13.0",
"framer-motion": "^11.11.11",
"react": "^18.3.1",
"react-dom": "^18.3.1"
},
"devDependencies": {
"@eslint/js": "^9.13.0",
"@types/react": "^18.3.12",
"@types/react-dom": "^18.3.1",
"@vitejs/plugin-react": "^4.3.3",
"eslint": "^9.13.0",
"eslint-plugin-react-hooks": "^5.0.0",
"eslint-plugin-react-refresh": "^0.4.14",
"globals": "^15.11.0",
"typescript": "~5.6.2",
"typescript-eslint": "^8.11.0",
"vite": "^5.4.10",
"vite-tsconfig-paths": "^5.0.1"
}
}
如您所见,我已经使用 typescript 安装了我的项目所需的必要依赖项。但是当我尝试在 main.tsx 中导入 ChakraProvider 时,如下所示:
import {ChakraProvider} from "@chakra-ui/react"
import React from "react"
import ReactDOM from "react-dom/client"
import App from "./App"
ReactDOM.createRoot(document.getElementById("root")!).render(
<React.StrictMode>
<ChakraProvider>
<App />
</ChakraProvider>
</React.StrictMode>,
)
我尝试将一个名为
value
的 prop 传递给 ChakraProvider,并给它一个值 undefined
,以便 TypeScript 可以在 props
中看到一些值。像这样:
<ChakraProvider value={undefined}>
但之后我收到此错误:
类型“未定义”不可分配给类型“SystemContext”.ts(2322)
provider.d.ts(4, 5):预期的类型来自属性“value”,该属性在类型“IntrinsicAttributes & ChakraProviderProps”上声明
这是为什么?我该如何解决?
value
属性允许您指定您的主题。如果您要更改 Chakra 的默认值,则可以传入自定义值,但否则您需要从 Chakra 传入 defaultSystem
:
import { defaultSystem } from "@chakra-ui/react"
...
<ChakraProvider value={defaultSystem}>
<App />
</ChakraProvider>