基于变量渲染组件 - reactjs [英] Render component based on a variable - reactjs
本文介绍了基于变量渲染组件 - reactjs的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想问一下,是否可以根据变量返回一个组件,我的想法是否可行:
I would like to ask, if its possible to return a component based on a variable, my idea if this is possible:
var location = this.props.location // Eg. Asia,Australia
<location+"HeaderComponent" />
我的问题是我需要单独手动导入所有组件.
My problem with this is I need to manually import all of my components individually.
这是我拥有的其他脚本:
This is other script that I have:
import AsiaHeaderComponent from "components/AsiaHeaderComponent.jsx";
import AustraliaHeaderComponent from "components/AustraliaHeaderComponent.jsx";
class Home extends React.Component {
renderHeader(){
if(this.props.location == "Asia"){
return (
<AsiaHeaderComponent />
);
}
else if(this.props.location == "Australia"){
return (
<AustraliaHeaderComponent />
);
}
}
render(){
return (
{ this.renderHeader() }
)
}
}
与上面一样,我需要手动导入所有将放在 if else 条件中的标题.
Same with above I need to manually import all of the header that will be put inside if else condition.
有没有办法有效地做到这一点?
is there a way to efficiently do this?
推荐答案
import AsiaHeaderComponent from "components/AsiaHeaderComponent.jsx";
import AustraliaHeaderComponent from "components/AustraliaHeaderComponent.jsx";
const componentOf = {
aisa: AsiaHeaderComponent,
australia: AustraliaHeaderComponent
};
class Home extends React.Component {
renderHeader(){
return componentOf[this.props.location]
}
render(){
return (
{ this.renderHeader() }
)
}
}
也许这样更好一点?
这篇关于基于变量渲染组件 - reactjs的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文