Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/467.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/reactjs/21.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如何替换React中的组件?_Javascript_Reactjs_Navigation - Fatal编程技术网

Javascript 如何替换React中的组件?

Javascript 如何替换React中的组件?,javascript,reactjs,navigation,Javascript,Reactjs,Navigation,我正在尝试使用React构建一个单页应用程序。目前,我有一个名为App的组件,它由ReactDOM呈现,它包含导航,然后是在导航组件之后呈现的组件(或页面) import React from 'react'; import Navigation from './Navigation'; import NavigationLink from './NavigationLink'; import Home from './Home'; import About from './About'; c


我正在尝试使用React构建一个单页应用程序。目前,我有一个名为
App
的组件,它由
ReactDOM
呈现,它包含导航,然后是在导航组件之后呈现的组件(或页面)

import React from 'react';
import Navigation from './Navigation';
import NavigationLink from './NavigationLink';
import Home from './Home';
import About from './About';

const App = () => (
  <div>
    <Navigation>
      <NavigationLink onClick={ ... }>Home</NavigationLink>
      <NavigationLink onClick={ ... }>About</NavigationLink>
    </Navigation>
    <Home />
  </div>
);

export default App;

TLDR:在构建应用程序主体的render()方法中,动态插入与您试图向用户显示的当前组件/模块/页面一致的React组件。

你完全可以使用React路由器。它已经建立并广泛使用。但是如果你愿意的话,你完全可以不用反应路由器。我也在构建一个单页应用程序,我也在交换组件,正如您所描述的。以下是实现这一目标的两个主要文件:

template.default.js:

// lots o' imports up here...

// styles/themes that are needed to support the drawer template

class DefaultTemplate extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            mainHeight : 200,
            mobileOpen : false,
            toolbarSpacerHeight : 100,
        };
        session[the.session.key.for.DefaultTemplate] = this;
        session.browser = detect();
    }

    getModule() {
        // here I'm switching on a session variable (which is available throughout the entire app to determine which module ID the user has currently chosen
        // notice that the return values are the dynamic React components that coincide with the currently-chosen module ID 
        switch (session.DisplayLayer.state.moduleId) {
            case the.module.id.for.home:
                return <HomeModule/>;
            case the.module.id.for.lists:
                return <ListsModule/>;
            case the.module.id.for.login:
                return <LogInModule/>;
            case the.module.id.for.logout:
                return <LogOutModule/>;
            case the.module.id.for.register:
                return <RegisterModule/>;
            case the.module.id.for.roles:
                return <RolesModule/>;
            case the.module.id.for.teams:
                return <TeamsModule/>;
            case the.module.id.for.users:
                return <UsersModule/>;
            default:
                return null;
        }
    }

    handleDrawerToggle = () => {
        this.setState({mobileOpen : !this.state.mobileOpen});
    };

    render() {
        // the module is dynamically generated every time a render() is invoked on this template module 
        const module = this.getModule();
        return (
            <div className={classes.root} style={{height : the.style.of.percent.hundred}}>
                <AppBar className={classes.appBar} style={{backgroundColor : the.color.for.appBar}}>
                    <Toolbar>
                        <IconButton
                            aria-label={the.ariaLabel.openDrawer}
                            className={classes.navIconHide}
                            color={the.style.of.inherit}
                            onClick={this.handleDrawerToggle}
                        >
                            <MenuIcon/>
                        </IconButton>
                        <FontAwesome name={the.icon.for.palette} style={{marginRight : '10px', fontSize : the.style.of.onePointFiveEms}}/>
                        <Typography variant={the.variant.of.title} color={the.style.of.inherit} noWrap>
                            <TranslatedText english={'Groupware'}/>.<TranslatedText english={'Studio'}/>
                        </Typography>
                        <LanguageMenu
                            containerStyle={{marginLeft : the.style.of.margin.auto}}
                            onClose={event => {this.updateLanguage(event)}}
                            selectedLanguageId={db.getItem(the.db.item.for.languageId)}
                        />
                    </Toolbar>
                </AppBar>
                <Hidden mdUp>
                    <Drawer
                        anchor={theme.direction === the.direction.of.rightToLeft ? the.direction.of.right : the.direction.of.left}
                        classes={{paper : classes.drawerPaper}}
                        ModalProps={{keepMounted : true}}
                        onClose={this.handleDrawerToggle}
                        open={this.state.mobileOpen}
                        variant={the.variant.of.temporary}
                    >
                        {drawer}
                    </Drawer>
                </Hidden>
                <Hidden smDown implementation={the.implementation.of.css}>
                    <Drawer
                        classes={{paper : classes.drawerPaper}}
                        open
                        variant={the.variant.of.permanent}
                    >
                        {drawer}
                    </Drawer>
                </Hidden>
                <main
                    className={classes.content}
                    ref={main => this.main = main}
                    style={{backgroundColor : the.color.for.module.background}}
                >
                    <div
                        className={classes.toolbar}
                        ref={toolbarSpacer => this.toolbarSpacer = toolbarSpacer}
                    />
                    {/*
                        here is where that dynamically-generated module is rendered inside the template 
                    */}
                    {module}
                </main>
            </div>
        );
    }
}

export default withStyles(styles, {withTheme : true})(DefaultTemplate);
//这里有很多进口。。。
//支持抽屉模板所需的样式/主题
类DefaultTemplate扩展了React.Component{
建造师(道具){
超级(道具);
此.state={
身高:200,
MobilePen:错,
高度:100,,
};
session[the.session.key.for.DefaultTemplate]=此;
session.browser=detect();
}
getModule(){
//在这里,我打开了一个会话变量(在整个应用程序中都可以使用它来确定用户当前选择了哪个模块ID)
//请注意,返回值是与当前选择的模块ID一致的dynamic React组件
交换机(session.DisplayLayer.state.moduleId){
用于.home的.module.id.case:
返回;
case.module.id.for.list:
返回;
案例.module.id.for.login:
返回;
用于注销的.module.id.for.logout的案例:
返回;
用于注册表的.module.id.case:
返回;
.module.id.for.roles的案例:
返回;
案例.module.id.for.teams:
返回;
对于.user.module.id.case:
返回;
违约:
返回null;
}
}
handleDrawerToggle=()=>{
this.setState({mobileOpen:!this.state.mobileOpen});
};
render(){
//每次在此模板模块上调用render()时,都会动态生成该模块
const module=this.getModule();
返回(
.
{this.updateLanguage(event)}
selectedLanguageId={db.getItem(the.db.item.for.languageId)}
/>
{抽屉}
{抽屉}
this.main=main}
style={{backgroundColor:the.color.for.module.background}
>
this.toolbarSpacer=toolbarSpacer}
/>
{/*
这里是在模板内呈现动态生成的模块的位置
*/}
{module}
);
}
}
使用样式导出默认值(样式,{withTheme:true})(DefaultTemplate);
和navigation.left.js:

// lots o' imports up here 

class LeftNavigation extends React.Component {
    listButtons = [];
    // this object controls the configuration of the nav links that show on the left side of the template
    navigation = {
        isLoggedIn : [
            {
                icon : the.icon.for.home,
                isFollowedByDivider : false,
                label : the.label.for.home,
                moduleId : the.module.id.for.home,
            },
            {
                icon : the.icon.for.powerOff,
                isFollowedByDivider : true,
                label : the.label.for.logOut,
                moduleId : the.module.id.for.logout,
            },
            {
                icon : the.icon.for.orderedList,
                isFollowedByDivider : false,
                label : the.label.for.lists,
                moduleId : the.module.id.for.lists,
            },
            {
                icon : the.icon.for.roles,
                isFollowedByDivider : false,
                label : the.label.for.roles,
                moduleId : the.module.id.for.roles,
            },
            {
                icon : the.icon.for.teams,
                isFollowedByDivider : false,
                label : the.label.for.teams,
                moduleId : the.module.id.for.teams,
            },
            {
                icon : the.icon.for.users,
                isFollowedByDivider : false,
                label : the.label.for.users,
                moduleId : the.module.id.for.users,
            },
        ],
        isLoggedOut : [
            {
                icon : the.icon.for.home,
                isFollowedByDivider : false,
                label : the.label.for.home,
                moduleId : the.module.id.for.home,
            },
            {
                icon : the.icon.for.powerOff,
                isFollowedByDivider : false,
                label : the.label.for.logIn,
                moduleId : the.module.id.for.login,
            },
            {
                icon : the.icon.for.registered,
                isFollowedByDivider : false,
                label : the.label.for.register,
                moduleId : the.module.id.for.register,
            },
        ],
    };

    populateListButtons() {
        // here we are generating an array of ListButtons that will comprise the left-hand navigation 
        this.listButtons = [];
        let buttonConfigs = [];
        switch (db.getItem(the.db.item.for.isLoggedIn)) {
            case true:
                buttonConfigs = this.navigation.isLoggedIn;
                break;
            case false:
                buttonConfigs = this.navigation.isLoggedOut;
                break;
            default:
                return;
        }
        buttonConfigs.forEach(buttonConfig => {
            let buttonIsEnabled = true;
            let fontAwesomeStyle = {fontSize : the.style.of.onePointFiveEms};
            let listItemStyle = {};
            let textStyle = {};
            switch (buttonConfig.label) {
                case the.label.for.logIn:
                    fontAwesomeStyle[the.style.property.name.of.color] = the.color.for.success;
                    break;
                case the.label.for.logOut:
                    fontAwesomeStyle[the.style.property.name.of.color] = the.color.for.error;
                    break;
                default:
                    if (session.DisplayLayer.state.moduleId === buttonConfig.moduleId) {
                        fontAwesomeStyle[the.style.property.name.of.color] = the.color.for.white.text;
                    } else {
                        fontAwesomeStyle[the.style.property.name.of.color] = the.color.for.headerBar;
                    }
                    break;
            }
            if (session.DisplayLayer.state.moduleId === buttonConfig.moduleId) {
                buttonIsEnabled = false;
                listItemStyle[the.style.property.name.of.backgroundColor] = the.color.for.selectedLeftNavButtonOrange;
                textStyle[the.style.property.name.of.color] = the.color.for.white.text;
            }
            this.listButtons.push(
                <ListItem
                    button={buttonIsEnabled}
                    key={`${buttonConfig.label}-listItem`}
                    // notice that when one of the left nav links is clicked, we are updating the moduleId value in session, 
                    // which dynamically determines which module shows up in the center panel
                    onClick={() => session.DisplayLayer.updateModuleId(buttonConfig.moduleId)}
                    style={listItemStyle}
                >
                    <ListItemIcon>
                        <FontAwesome name={buttonConfig.icon} style={fontAwesomeStyle}/>
                    </ListItemIcon>
                    <TranslatedText english={buttonConfig.label} style={textStyle}/>
                </ListItem>,
            );
            if (buttonConfig.isFollowedByDivider) {
                this.listButtons.push(<Divider key={`${buttonConfig.label}-divider`}/>);
            }
        });
    }

    render() {
        // dynamically generate the array of left nav buttons before rendering the links 
        this.populateListButtons();
        return <List style={{paddingTop : the.style.of.pixels.zero}}>{this.listButtons}</List>;
    }
}

export default LeftNavigation;
//这里有大量导入
类LeftNavigation扩展了React.Component{
listButtons=[];
//此对象控制显示在模板左侧的导航链接的配置
导航={
伊斯洛格丁:[
{
icon:the.icon.for.home,
IsFollowByDivider:false,
标签:the.label.for.home,
moduleId:the.module.id.for.home,
},
{
icon:the.icon.for.powerOff,
IsfollowByDivider:对,
label:the.label.for.logOut,
moduleId:the.module.id.for.logout,
},
{
icon:the.icon.for.orderedList,
IsFollowByDivider:false,
label:the.label.for.lists,
moduleId:the.module.id.for.list,
},
{
icon:the.icon.for.roles,
IsFollowByDivider:false,
label:the.label.for.roles,
moduleId:for.roles的.module.id,
},
{
icon:the.icon.for.teams,
IsFollowByDivider:false,
label:the.label.for.teams,
moduleId:for.teams的.module.id,
},
{
icon:the.icon.for.users,
IsFollowByDivider:false,
label:the.label.for.users,
moduleId:for.users的.module.id,
},
],
伊斯洛格杜特:[
{
icon:the.icon.for.home,
IsFollowByDivider:false,
标签:the.label.for.home,
moduleId:the.module.id.for.home,
},
{
icon:the.icon.for.powerOff,
IsFollowByDivider:false,
label:the.label.for.logIn,
moduleId:the.module.id.for.login,
},
{
icon:the.icon.for.registered,
IsFollowByDivider:false,
label:the.label.for.register,
moduleId:for.register的.module.id,
},
// lots o' imports up here 

class LeftNavigation extends React.Component {
    listButtons = [];
    // this object controls the configuration of the nav links that show on the left side of the template
    navigation = {
        isLoggedIn : [
            {
                icon : the.icon.for.home,
                isFollowedByDivider : false,
                label : the.label.for.home,
                moduleId : the.module.id.for.home,
            },
            {
                icon : the.icon.for.powerOff,
                isFollowedByDivider : true,
                label : the.label.for.logOut,
                moduleId : the.module.id.for.logout,
            },
            {
                icon : the.icon.for.orderedList,
                isFollowedByDivider : false,
                label : the.label.for.lists,
                moduleId : the.module.id.for.lists,
            },
            {
                icon : the.icon.for.roles,
                isFollowedByDivider : false,
                label : the.label.for.roles,
                moduleId : the.module.id.for.roles,
            },
            {
                icon : the.icon.for.teams,
                isFollowedByDivider : false,
                label : the.label.for.teams,
                moduleId : the.module.id.for.teams,
            },
            {
                icon : the.icon.for.users,
                isFollowedByDivider : false,
                label : the.label.for.users,
                moduleId : the.module.id.for.users,
            },
        ],
        isLoggedOut : [
            {
                icon : the.icon.for.home,
                isFollowedByDivider : false,
                label : the.label.for.home,
                moduleId : the.module.id.for.home,
            },
            {
                icon : the.icon.for.powerOff,
                isFollowedByDivider : false,
                label : the.label.for.logIn,
                moduleId : the.module.id.for.login,
            },
            {
                icon : the.icon.for.registered,
                isFollowedByDivider : false,
                label : the.label.for.register,
                moduleId : the.module.id.for.register,
            },
        ],
    };

    populateListButtons() {
        // here we are generating an array of ListButtons that will comprise the left-hand navigation 
        this.listButtons = [];
        let buttonConfigs = [];
        switch (db.getItem(the.db.item.for.isLoggedIn)) {
            case true:
                buttonConfigs = this.navigation.isLoggedIn;
                break;
            case false:
                buttonConfigs = this.navigation.isLoggedOut;
                break;
            default:
                return;
        }
        buttonConfigs.forEach(buttonConfig => {
            let buttonIsEnabled = true;
            let fontAwesomeStyle = {fontSize : the.style.of.onePointFiveEms};
            let listItemStyle = {};
            let textStyle = {};
            switch (buttonConfig.label) {
                case the.label.for.logIn:
                    fontAwesomeStyle[the.style.property.name.of.color] = the.color.for.success;
                    break;
                case the.label.for.logOut:
                    fontAwesomeStyle[the.style.property.name.of.color] = the.color.for.error;
                    break;
                default:
                    if (session.DisplayLayer.state.moduleId === buttonConfig.moduleId) {
                        fontAwesomeStyle[the.style.property.name.of.color] = the.color.for.white.text;
                    } else {
                        fontAwesomeStyle[the.style.property.name.of.color] = the.color.for.headerBar;
                    }
                    break;
            }
            if (session.DisplayLayer.state.moduleId === buttonConfig.moduleId) {
                buttonIsEnabled = false;
                listItemStyle[the.style.property.name.of.backgroundColor] = the.color.for.selectedLeftNavButtonOrange;
                textStyle[the.style.property.name.of.color] = the.color.for.white.text;
            }
            this.listButtons.push(
                <ListItem
                    button={buttonIsEnabled}
                    key={`${buttonConfig.label}-listItem`}
                    // notice that when one of the left nav links is clicked, we are updating the moduleId value in session, 
                    // which dynamically determines which module shows up in the center panel
                    onClick={() => session.DisplayLayer.updateModuleId(buttonConfig.moduleId)}
                    style={listItemStyle}
                >
                    <ListItemIcon>
                        <FontAwesome name={buttonConfig.icon} style={fontAwesomeStyle}/>
                    </ListItemIcon>
                    <TranslatedText english={buttonConfig.label} style={textStyle}/>
                </ListItem>,
            );
            if (buttonConfig.isFollowedByDivider) {
                this.listButtons.push(<Divider key={`${buttonConfig.label}-divider`}/>);
            }
        });
    }

    render() {
        // dynamically generate the array of left nav buttons before rendering the links 
        this.populateListButtons();
        return <List style={{paddingTop : the.style.of.pixels.zero}}>{this.listButtons}</List>;
    }
}

export default LeftNavigation;
addComponent = async type => {
  console.log(`Loading ${type} component...`);

  import(`./components/${type}.js`)
    .then(component =>
      this.setState({
        components: this.state.components.concat(component.default)
      })
    )
    .catch(error => {
      console.error(`"${type}" not yet supported`);
    });
};
getComponent(){
    let component;
    switch (this.state.currentComponent){
        case 'compA' :
            component = <CompA/>;
            break;
        case 'compB' :
            component = <CompB/>;
            break;
        case 'compC' :
            component = <CompC/>;
            break;
        case 'compD' :
            component = <CompD/>;
            break;
    }
    return component;
}

render(){
    return(
        <div>
            {this.getComponent()}
        </div>
    );
}