假设我有一个名为 CountryFlag
的 React.js 组件。我在 countries/
此组件采用单个属性 - 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/