JS/React 使用动态值进行导入

问题描述 投票:0回答:1

Next.js 附带了一堆“内置”字体,您可以像这样导入:

import { Poppins } from "next/font/google";

const setFont = Poppins({weight: ['300'] , subsets: ["latin"] });

然后你可以将它实现到代码中的字体中,如下所示:

    <html>
        <body className={setFont.className}>
          {children}
        </body>
    </html>

我希望能够像这样动态地进行导入:

let theFont= "Poppins"

import { {theFont} } from "next/font/google";

const setFont = theFont({weight: ['300'] , subsets: ["latin"] });

我尝试将其包装到一个函数中,而您无法使用这样的导入来执行此操作,并且尝试在导入语句中获取动态值,但这也不起作用,但我可能弄乱了语法

javascript reactjs next.js frontend
1个回答
0
投票

首先想到的是通过

*
导入所有命名的导出,然后通过变量引用特定符号

import * as fonts from 'next/font/google';

let theFont = 'Poppins';

const setFont = fonts[theFont]({ weight: ['300'], subsets: ['latin'] });

当然,你会失去任何摇树的机会,但这就是你为动态而付出的代价。

© www.soinside.com 2019 - 2024. All rights reserved.