javascript - 如何根据 prop 的值使用 React.js、ES6 和 Webpack 导入文件?

标签 javascript reactjs webpack ecmascript-6

假设我有一个名为 CountryFlag 的 React.js 组件。我在 countries/

也有每个国家国旗的 SVG 图像目录

此组件采用单个属性 - countryCode。这将是诸如西类牙的 ES

this.props 不在范围内时,如何将 ES6 import 构造与 this.props.countryCode 一起使用?

我曾尝试在 componentDidMount() 中执行此操作,但出现语法错误:

Syntax error: 'import' and 'export' may only appear at the top level (6:2)

最佳答案

你应该使用require。喜欢:

class Whatever extends Component{
  constructor(props) {
    super(props);
    this.countryImage = null;
  }
  componentDidMount() {
    const { countryCode } = this.props;
    this.countryImage = require(`./countries/${countryCode}.svg`); 
  }
  render() {
    return (
      <img src={this.countryImage} alt="Whatever" />
    );
  }
}

关于javascript - 如何根据 prop 的值使用 React.js、ES6 和 Webpack 导入文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42366261/

相关文章:

javascript - Sequelize 播种机找不到模型的正确列名称

javascript - 错误: Cannot find module "expose?Zone!zone.js"

jquery - 在 React 的 JSX 中初始化 jQuery 函数

node.js - 尝试将 mongoose 与 webpack 结合使用时出现大量神秘错误和警告

javascript - Nuxtjs如何在为组件导入css文件时为npm run generate配置webpack?

javascript - 在 javascript 或 momentjs 中获取给定的日期格式(指定格式的字符串)

javascript - 从ListView中获取选定的记录

javascript - Mobx 在 Action 之外改变可观察值

windows - Electron - 分发构建中的文件路径问题

javascript - React.js 包含 css