[英]How can I import a file using React.js, ES6 and Webpack based on the value of a prop?
Let's say I have a React.js component called CountryFlag
. 假设我有一个名为CountryFlag
的React.js组件。 I also have a directory of SVG images for each country's flag at countries/
我还为每个countries/
地区的国旗提供了SVG图片目录
This component takes a single prop - countryCode
. 该组件采用单个prop- countryCode
。 This would be something such as ES
for Spain. 例如西班牙的ES
。
How can I use the ES6 import
construct with this.props.countryCode
when this.props
is not in scope? 当this.props
不在范围内时,如何将ES6 import
构造与this.props.countryCode
this.props
?
I have tried to do this in componentDidMount()
but get a syntax error: 我尝试在componentDidMount()
执行此操作,但收到语法错误:
Syntax error: 'import' and 'export' may only appear at the top level (6:2)
You should use require
. 您应该使用require
。 like: 喜欢:
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" />
);
}
}
You can make use of System.import
to import
a component dynamically in componentDidMount
您可以利用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;
}
You can also use your props on src to your image. 您也可以将src上的道具用于图像。 Something like <img src={"./img/" + this.props.country + ".svg"}>
类似于<img src={"./img/" + this.props.country + ".svg"}>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.