我开始学习 Typescript 和 SolidJS,然后我遇到了这个。
import { Component } from "solid-js"
const Button:Component=({onClick})=>{
return <button onClick={onClick}>Button</button>
}
export default Button
我创建的每个组件都充满了错误高亮,但项目运行正常,甚至是传入的函数
onClick
。
可能是 vscode 配置错误?我通常在 React 中编码。
文件扩展名是 tsx:
tsconfig.json
{
"compilerOptions": {
"strict": true,
"target": "ESNext",
"module": "ESNext",
"moduleResolution": "node",
"allowSyntheticDefaultImports": true,
"esModuleInterop": true,
"jsx": "preserve",
"jsxImportSource": "solid-js",
"types": ["vite/client"],
"noEmit": true,
"isolatedModules": true,
"paths": {
"@": ["./src"],
"@/*": ["./src/*"],
"$lib":["./src/lib"],
"$lib/*":["./src/lib/*"]
}
}
}
存储库solidjs
核心模块中的
Component
类型用于注释 SolidJS 组件。它对于 Props
对象是通用的。
让我们看看它的定义:
/**
* A general `Component` has no implicit `children` prop. If desired, you can
* specify one as in `Component<{name: String, children: JSX.Element>}`.
*/
export declare type Component<P = {}> = (props: P) => JSX.Element;
因为你的组件只有一个 prop,
onClick
,并且它将点击事件作为其唯一参数。点击事件具有 MouseEvent
类型:
import { Component } from "solid-js"
interface ButtonProps {
onClick: (event: MouseEvent) => void
}
const Button: Component<ButtonProps> =({ onClick })=>{
return (
<button onClick={onClick}>Button</button>
);
}
export default Button;
我创建的每个组件都充满错误高亮,但项目运行正常,甚至onClick中传入的函数也是如此。
Typescript 是一个辅助工具,组件只要编译为 JavaScript 且没有任何错误就可以工作。
如果您不向
Component
提供自己的道具类型,道具将是普通对象,因为它默认为P = {}
。
您会收到错误,因为您的按钮组件期望
{}
作为其 prop,但您正在传递 { onClick: (event: MouseEvent) => void }
。
可能是 vscode 配置错误?我通常在 React 中编码。
可能它与 vscode 无关,因为它内置了对 typescript 的支持,这意味着如果它安装在您的
package.json
中并且具有 tsconfig.json
,您不需要任何扩展即可使用 typescript。
Solid 组件的类型签名与 React 的不同。用 React 的术语来说,Solid 只有函数组件,并且不会将状态传递给其子组件,因此 Solid 的
S = {}
类型中没有 Component
。