Reactjs 如何使用基于状态的道具组织React动态组件
我需要根据状态显示特定组件。为了做到这一点,我创建了一个对象,它根据活动选项卡索引定义要显示的组件。然而,这个对象将是巨大的,我不希望它在Reactjs 如何使用基于状态的道具组织React动态组件,reactjs,Reactjs,我需要根据状态显示特定组件。为了做到这一点,我创建了一个对象,它根据活动选项卡索引定义要显示的组件。然而,这个对象将是巨大的,我不希望它在App.js中占用数千行。然而,这些动态组件需要的许多道具都是从应用程序的状态派生出来的。我有没有办法把组件拉到它自己的js文件中,仍然可以访问应用程序的状态和功能来设置道具 在App.js中: components = () => { return { Standard: { 0:
App.js
中占用数千行。然而,这些动态组件需要的许多道具都是从应用程序的状态派生出来的。我有没有办法把组件
拉到它自己的js文件中,仍然可以访问应用程序的状态和功能来设置道具
在App.js中:
components = () => {
return {
Standard: {
0: {
comp: StandardOverview,
props: {
overview: this.state.overview,
enroll: this.doEnroll
}
},
1: {
comp: AccountActivity,
props: {
account: this.props.account,
accountData: this.state.accountData
}
}
},
Special: {
0: {
comp: SpecialOverview,
props: {
overview: this.state.overview,
enroll: this.doEnrollSpecial
}
},
1: {
comp: Communications,
props: {
subscriptions: this.state.subscriptions,
mobilePhone: this.state.mobilePhone,
onSubscribeClick: this.onSubscribeClick
}
}
}
}
};
render() {
const contentForIndex = this.components()[this.state.profileType || "Standard"][this.state.activeIndex];
const ContentComponent = contentForIndex.comp;
const props = contentForIndex.props;
return (
<ErrorHandler>
<ContentComponent {...props} />
</ErrorHandler>
)
}
components=()=>{
返回{
标准:{
0: {
公司:标准概述,
道具:{
概述:this.state.overview,
注册:这是doEnroll
}
},
1: {
公司:会计活动,
道具:{
账户:this.props.account,
accountData:this.state.accountData
}
}
},
特别:{
0: {
comp:SpecialLoverView,
道具:{
概述:this.state.overview,
注册:这是一个特殊的
}
},
1: {
公司:通讯,
道具:{
订阅:this.state.subscriptions,
手机:这个州,手机,
onSubscribeClick:this.onSubscribeClick
}
}
}
}
};
render(){
const contentForIndex=this.components()[this.state.profileType | | |“Standard”][this.state.activeIndex];
const ContentComponent=contentForIndex.comp;
const props=contentForIndex.props;
返回(
)
}
我会稍微改变一下。与其让组件
返回一个对象,为什么不直接将其转换为react组件,该组件使用开关根据道具将正确的子组件返回到组件
像这样:
components = props => {
switch(props.yourMainKey){
case 'standard':
return (
<StandardOverview
overview={props.overview}
{...anyOtherProps}
/>
)
case 'Special':
return (
<SpecialOverview overview={props.overview} />
)
default:
return (
<DefaultView overview={props.defaultProps} />
)
}
}
components=props=>{
开关(props.YourMain键){
案例“标准”:
返回(
)
特殊情况:
返回(
)
违约:
返回(
)
}
}
您可以使用react路由器。基本上,react会劫持浏览器历史记录,您可以根据URL呈现不同的组件/home
=>standardcoverview
,/account/
=>AccountActivity
等等这对我真的没有帮助,因为那样我就需要嵌套的switch语句了。我不仅需要知道profileType是标准的还是特殊的(或其他10个值),还需要知道活动选项卡是什么。这基本上与使用giant对象相同,只是现在我有了一个giant switch语句。是的,但是使用giant switch语句,您可以删除一级嵌套,因为开关本身就是一个react组件,而且它解决了您提出的问题:“有没有办法将组件拉到自己的js文件中?”。如果您不想处理一个巨大的组件或对象,那么就使用路由库,这正是它们的用途。