2017-02-21 65 views
0

比方说,我有一个名为CountryFlag的React.js组件。我也有一个每个国家的国旗的SVG图像目录countries/如何根据道具的值使用React.js,ES6和Webpack导入文件?

这个组件采取一个单一的道具 - countryCode。这将是诸如ES西班牙。

this.props不在范围内时,如何使用带有this.props.countryCode的ES6 import结构?

我试图做到这一点在componentDidMount()却得到了一个语法错误:

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

你不会做到这一点,你刚才提到的URL并在CDN –

+0

不能导入基于属性的东西将图片(据我所知)。会有这样的帮助吗? :https://github.com/matthewwithanm/react-inlinesvg你可以在组件导入Isvg模块,然后有Isvg src作为属性值'' – Jayce444

+0

@ CallumLinington:我会做,但我捆绑它进行生产,需要使用Webpack来做到这一点。 –

回答

1

您可以使用System.importimport组件动态地componentDidMount

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; 
} 
+0

谢谢!这将允许Webpack捆绑SVG吗? –

+1

为什么正好导入而不需要?前者会导致一个新的块,这可能是也可能不是理想的行为。 – estus

+0

我不确定,但它应该可以帮助你捆绑svg。你可以试试看。 –

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" /> 
    ); 
    } 
} 
+0

这是否与Webpack捆绑SVG一起工作? –

1

你也可以用你的道具上的src到你的形象。 喜欢的东西 <img src={"./img/" + this.props.country + ".svg"}>

+0

这不会阻止Webpack捆绑SVG吗? –

+0

真的不知道,但我没有问题。只需写入正确的图像路径) – Andrew