【问题标题】:Extending the default behaviour of React.FC in Nextjs在 Nextjs 中扩展 React.FC 的默认行为
【发布时间】:2020-08-09 20:52:56
【问题描述】:

所以我有一个在 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;
}

我想向我的功能组件添加一个方法。

【问题讨论】:

    标签: javascript reactjs typescript next.js


    【解决方案1】:

    尝试将您的接口与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

    【讨论】:

    • 我在代码中犯了一个错误,我使用了“&&”而不是“&”。谢谢。虽然我使用了你的解决方案,但我删除了静态声明
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多