[英]How to get auto-suggestion when we style a components inside react.js file?
[英]How to configure types in JavaScript file for getting auto-suggestion?
在 Javascript 文件中获取自动建议(带类型)应该配置什么?
换句话说,给定一个用 JS 编写的组件,如何获得其 props 的自动建议(有可能,请阅读所有问题)。
我正在尝试获取简单 Button 组件的自动建议(以获取“红色”或“蓝色”的建议), 类似于 MUI 中的组件。
// Would like the IDE so suggest "red" or "blue" on changing color prop
const App = () => {
return <Button color="red" />;
};
// Button.js
import React from "react";
const Button = ({ color }) => <button style={{ color }}>Button</button>;
export default Button;
// ButtonTypes.d.ts
export interface Button {
color: "red" | "blue";
}
在此处查看更改。
// Button.d.ts
import * as React from "react";
declare const Button: React.FC<{
color: "red" | "blue";
}>;
export default Button;
// App.js
const App = () => {
return (
<>
{/* Auto-suggests "red" and "blue" */}
<Button color="red" />
</>
);
};
您需要将.d.ts
文件命名为与.js
相同的名称。 此外,您需要声明Button
,而不仅仅是道具。
尽管@bengr给出了一个很好的答案,但是在 JSDocs 中有一个使用 Typescript 的替代方法,它允许 javascript 文件中的语义错误:
// App.js
// @ts-check
const App = () => {
return (
<>
<Button color="red" />
{/* Shows a WARNING! */}
<Button color={null} />
</>
);
};
// types.ts
import type { CSSProperties, FunctionComponent } from "react";
export type ButtonComponent = FunctionComponent<{color: CSSProperties["color"]}>;
// Button.js
import React from "react";
/**
* @type {import("./types").ButtonComponent}
*/
const Button = ({ color }) => <button style={{ color }}>Button</button>;
export default Button;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.