![](/img/trans.png)
[英]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.