【问题标题】:How can I import a file using React.js, ES6 and Webpack based on the value of a prop?如何根据 prop 的值使用 React.js、ES6 和 Webpack 导入文件?
【发布时间】:2017-07-11 00:18:59
【问题描述】:

假设我有一个名为 CountryFlag 的 React.js 组件。我在countries/也有每个国家国旗的 SVG 图像目录@

此组件采用单个道具 - countryCode。这将是诸如 ES 对于西班牙。

this.props 不在作用域内时,我如何使用带有this.props.countryCode 的ES6 import 构造?

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

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

【问题讨论】:

  • 你不会这样做,你只需引用他们的 url 并将图像托管在 CDN 上
  • 你不能导入基于属性的东西(据我所知)。这样的事情会有帮助吗? :github.com/matthewwithanm/react-inlinesvg你可以在组件中导入Isvg模块,然后将Isvg src作为属性值<Isvg src={this.props.svgImage}/>
  • @CallumLinington:我会这样做,但我将它打包用于生产,需要使用 Webpack 来完成。
  • @Jayce444:谢谢!

标签: javascript reactjs webpack ecmascript-6


【解决方案1】:

您应该使用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" />
    );
  }
}

【讨论】:

    【解决方案2】:

    您可以在componentDidMount 中动态使用System.importimport 的组件

    constructor(props) {
      super(props)
    
      this.state = { component: null }
    }
    componentDidMount() {
        this.loadComponent(component => this.setState({ component }));
    }
    loadComponent = callback => {
        let component = null;
        // This needs to be relative to the current module otherwise Webpack won't know where to look
        System.import(`./countries/${this.props.countryCode}`).then(module => callback(component = module))
        return component;
    }
    

    【讨论】:

    • 谢谢!这会允许 Webpack 捆绑 SVG 吗?
    • 为什么完全导入而不需要?前者会产生一个新的块,这可能是也可能不是理想的行为。
    • 好吧,我不确定,但它也应该可以帮助您捆绑 svg。你可以试试看。
    • System.import is deprecated 并已替换为 import()(函数)
    【解决方案3】:

    您还可以将 src 上的道具用于您的图像。 就像是 &lt;img src={"./img/" + this.props.country + ".svg"}&gt;

    【讨论】:

    • 这不会阻止 Webpack 捆绑 SVG 吗?
    • 真的不确定,但我对此没有任何问题。只需写入正确的图像路径)
    猜你喜欢
    • 1970-01-01
    • 2016-03-01
    • 2016-11-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-15
    • 1970-01-01
    • 2017-07-25
    相关资源
    最近更新 更多