【问题标题】:Dynamic Imports Based on this.props in ReactReact 中基于 this.props 的动态导入
【发布时间】:2026-02-02 23:00:02
【问题描述】:

在我的 NextJS 应用程序中,我有 node_modules(js 文件)用于页面上某些元素的主题。我只想根据组件的 this.props.theme 加载我需要的文件。我将如何/在我的组件中执行此操作。基本上,如果我有一堆主题文件:

theme-red.js
theme-orange.js
theme-yellow.js
theme-green.js
theme-blue.js
theme-purple.js
theme-violet.js
theme-pink.js
theme-rainbow.js

在道具中,我会this.props.theme传入然后加载require(theme-${this.props.theme}.js)

【问题讨论】:

    标签: javascript node.js reactjs next.js


    【解决方案1】:

    你可以使用import函数:

    const 主题 = 等待导入(./{path-to-the-files}/theme-${this.props.theme}.js)

    最好将它包含在组件的componentWillMount 函数中。

    https://nextjs.org/docs/advanced-features/dynamic-import
    https://javascript.info/modules-dynamic-imports

    【讨论】: