這是我試圖實作的代碼行。
const MaybeBigHeading = styled(Heading)( ({ big:boolean = false }) => [ big && tw`text-4xl` ]);
我收到的錯誤是:
Property 'big' does not exist on type 'ClassAttributes<HTMLHeadingElement> & HTMLAttributes<HTMLHeadingElement> & { theme?: Theme | undefined; } & { ...; }'.ts(2339)
這個錯誤對我來說很有意義,但我正在學習 ReactJS/Typescript 并試圖從 Javascript 教程中實作一些東西;這適用于 Javascript,但不適用于 Typescript。
不知道如何在 Typescript 中解決這個問題。
uj5u.com熱心網友回復:
發布后不久找到了解決方案
通過添加
declare module "react" {
interface HTMLAttributes<T> extends DOMAttributes<T> {
big?: boolean;
}
}
到 .tsx 檔案,我可以使用“big”作為新組件的屬性
完整的 App.tsx 檔案如下
/** @jsxImportSource @emotion/react */
import tw from "twin.macro";
import { DOMAttributes } from "react";
import styled from "@emotion/styled";
const Heading= tw.h1`text-blue-500 text-2xl p-2`;
const BigHeading = tw(Heading)`text-4xl`;
declare module "react" {
interface HTMLAttributes<T> extends DOMAttributes<T> {
big?: boolean;
}
}
const MaybeBigHeading = styled(Heading)( ({ big = false }) => [ big && tw`text-4xl text-red-300` ]);
const Container = tw.div`max-w-4xl mx-auto p-5 mt-5`;
function App() {
return (
<Container >
<BigHeading>Hello World</BigHeading>
<Heading>This is an example</Heading>
<MaybeBigHeading>This might be a Big Heading</MaybeBigHeading>
<MaybeBigHeading big>This IS a Big Heading</MaybeBigHeading>
</Container>
);
}
export default App;
uj5u.com熱心網友回復:
該styled函式的型別稱為泛型。泛型允許您通過引數傳入自己的型別。通用引數放在尖括號 ( <>) 之間。在你的情況下,你會像這樣使用它:
const MaybeBigHeading = styled(Heading)<{ big?: boolean; }>(({ big = false }) => [ big && tw`text-4xl text-red-300` ]);
另請參閱有關將TypeScript 與 Emotion 結合使用的檔案。您可以在此處了解如何styled定義for 的泛型型別。
關于您發現的解決方案的說明
在您發現的解決方案中,您HTMLAttributes通過添加自己的型別擴展了介面big:
declare module "react" {
interface HTMLAttributes<T> extends DOMAttributes<T> {
big?: boolean;
}
}
是的,這是可行的,但它本質上是一種在沒有其他選擇時使用的蠻力方法。這不是一個好主意,因為它污染了 HTML 屬性的含義,并且可能會給您的代碼的未來讀者(可能是您自己)造成混淆。big不是 HTML 屬性,因此不應存在于 HTML 屬性界面上。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/323446.html
上一篇:我們如何將顏色作為道具傳遞?
