簡體   English   中英

在 Nextjs 中擴展 React.FC 的默認行為

[英]Extending the default behaviour of React.FC in Nextjs

所以我有一個在 Nextjs 中使用以下代碼的教程,我計划將它從 javascript 移動到 typescript。 我是 typescript 的新手,所以我已經嘗試了我見過的大部分文章,但擴展默認的 React.FC 似乎不起作用。

function Explore() {
  return <p className="p-4">Explore</p>;
}

Explore.headerTitle = "Search";

export default Explore;

我的組件


const Home: React.FunctionComponent = () => {
    
    return (
        <div>
            <Head>
                <title>Home / Twitter</title>
                <link rel="icon" href="/favicon.ico" />
            </Head>

            <div>
                <p>Hello </p>
            </div>
        </div>
    );
};
Home.headerTitle = "Search";

我的界面

export interface HeaderTitle extends React.FunctionComponent {
    headerTitle: string;
}

我想向我的功能組件添加一個方法。

嘗試將您的接口與React.FunctionComponent分開聲明(為了可重用性):

export interface WithHeaderTitle {
   static headerTitle?: string;
}

然后在您的組件代碼中,導入接口並像這樣使用它:

const Home: React.FunctionComponent & WithHeaderTitle = () => { ... }

這里的關鍵字是“交叉點類型”。 您可以在這里閱讀更多相關信息: https://www.typescriptlang.org/docs/handbook/unions-and-intersections.html#intersection-types

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM