[英]How can I import a file using React.js, ES6 and Webpack based on the value of a prop?
假设我有一个名为CountryFlag
的React.js组件。 我还为每个countries/
地区的国旗提供了SVG图片目录
该组件采用单个prop- countryCode
。 例如西班牙的ES
。
当this.props
不在范围内时,如何将ES6 import
构造与this.props.countryCode
this.props
?
我尝试在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" />
);
}
}
您可以利用System.import
在componentDidMount中动态import
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;
}
您也可以将src上的道具用于图像。 类似于<img src={"./img/" + this.props.country + ".svg"}>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.