为了账号安全,请及时绑定邮箱和手机立即绑定

在 Nextjs 中扩展 React.FC 的默认行为

在 Nextjs 中扩展 React.FC 的默认行为

慕斯王 2022-12-29 10:28:24
所以我有一个在 Nextjs 中使用以下代码的教程,我计划将它从 javascript 转移到 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;}我想向我的功能组件添加一个方法。
查看完整描述

1 回答

?
人到中年有点甜

TA贡献1895条经验 获得超7个赞

尝试单独声明您的接口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


查看完整回答
反对 回复 2022-12-29
  • 1 回答
  • 0 关注
  • 75 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信