gpt4 book ai didi

javascript - 如何根据 prop 的值使用 React.js、ES6 和 Webpack 导入文件?

转载 作者:行者123 更新时间:2023-11-30 09:38:25 25 4
gpt4 key购买 nike

假设我有一个名为 CountryFlag 的 React.js 组件。我在 countries/

也有每个国家国旗的 SVG 图像目录

此组件采用单个属性 - 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com