根据路由改变组件的样式 - 反应路由器

时间:2021-02-21 17:43:01

标签: reactjs react-router styled-components

我知道如何做到这一点,但我想问一下是否有更好的方法?我有一个在两条不同路线上完全相同的组件,唯一改变的是其中的组件。看起来像这样。

/conjugation/config/:id

enter image description here

/conjugation/quiz

enter image description here

如您所见,它们都是相同的,目前我为它们提供了两个组件,用于渲染包装器和其中的组件。但是,我可以在两个组件 QuizCardConfigCard 之间共享包装器,并根据路由更改任何布局:

方式一:

const Conjugation = (props) => {

    const {match} = props;

    return (
        <>
            <Route exact path={`${match.url}/`} component={HowTo}/>
            <Route path={[match.url + "/config/:id", match.url + "/quiz"]}>
                <PageWrapper>
                    <Route path={`${match.url}/config/:id`} component={ConfigCard}/>
                    <Route exact path={`${match.url}/quiz`} component={QuizCard} />
                </PageWrapper>
            </Route>
            <SvgWaveTop />
            <QuizSelectSideBar />
       </>
    )
}

其中 Config and Quiz 卡片被包裹在一个 Wrapper 组件(styled-components)中,这是一个带有橙色边框的框...

方式二:

const Conjugation = (props) => {

    const {match, location} = props;

    const relativePath = location.pathname.replace(match.path, "");
    return (
        <>
            <Route exact path={`${match.url}/`} component={HowTo}/>
            <Route path={[match.url + "/config/:id", match.url + "/quiz"]}>
                <PageWrapper>
                   <MainCardContainer relativePath={relativePath}>
                       <Route path={`${match.url}/config/:id`} component={ConfigCard}/>
                       <Route exact path={`${match.url}/quiz`} component={QuizCard} />
                   </MainCardContainer>
                </PageWrapper>
            </Route>
            <SvgWaveTop />
            <QuizSelectSideBar />
       </>
    )
}

道具“relativePath”决定了给定路径的样式,这里有一个switch语句。 MainCardContainer 是带有橙色边框的框,只是为了澄清。

我的问题是,是否值得采用方式 2,或者我应该保持简单并采用方式 1?做方式 2 是否意味着 Wrapper "MainCardContainer" 在从 config 路由更改为 quiz 路由时不会重新渲染?

0 个答案:

没有答案
相关问题