【问题标题】:React - can a component be styled depending on what other component is rendered?React - 可以根据呈现的其他组件来设置组件的样式吗?
【发布时间】:2021-07-20 17:37:24
【问题描述】:

我有一个搜索组件,当主页组件呈现时,我希望搜索组件呈现在页面底部。当呈现任何其他页面组件时,我希望 Search 组件位于页面顶部。

目前我的 app.js 为:

const App = () => {
  return (
    <BrowserRouter>
      <Switch>
        <Route path='/' component={Home} />
        <Route path='/about' component={About} />
        <Route path='/work' component={Work} />
        <Route path='/contact' component={Contact} />
      </Switch>
    </BrowserRouter>
  )
}

在页面组件内部:

const Contact = () => {
    return (
      <div>
        <Search />
        Contact
      </div>
    )
}

显然,这种方式意味着我必须将 Search 组件添加到每个组件中,并选择将其放置在顶部还是底部。

我的问题是这样的,我可以像这样将它放在 app.js 上吗:

const App = () => {
  return (
    <BrowserRouter>
      <Search />
      <Switch>
        <Route path='/' component={Home} />
        <Route path='/about' component={About} />
        <Route path='/work' component={Work} />
        <Route path='/contact' component={Contact} />
      </Switch>
    </BrowserRouter>
  )
}

然后根据要呈现的页面组件,设置搜索组件的样式,使其显示在页面的顶部或底部。

谢谢

【问题讨论】:

标签: javascript css reactjs react-router jsx


【解决方案1】:

我会在 Search 组件中添加一个 className 属性并添加一些 if 语句。 例如:

<Search className={location === '/' ? 'top' : 'bottom'} />

【讨论】:

  • 谢谢你,一直在玩它,我一直收到错误:TypeError: useContext(...) is undefined 我没有在这个项目中使用 TypeScript。但是,我在 App.js 文件中使用 useLocation,而不是在每个单独的组件中,有什么想法吗?谢谢
  • @Cal 你为什么不想在每个单独的文件中使用这个钩子?这里没有问题。钩子就是为此而生的。
  • 在我看来,将 Search 组件放在其他每个组件(Home、About、Work 和 Contact)中有点不必要。我试图找到一种仅在 Switch 外部的 App.js 中使用 Search 组件的方法。然后根据呈现的页面组件,它将显示在顶部或底部。在每个单独的文件中的 Search 组件上使用 useLocation 固然有用,而且我将在其他地方使用,但这并不能解决我最初的问题。再次感谢您向我展示 useLocation,因为它非常酷!
【解决方案2】:

使用 React Router 提供的 useLocation() 钩子,你可以确定你在哪个页面。

const Contact () => {
  const location = useLocation();

  const styles = location === "something" ? {...topStyles} : {...downStyles};

  return (
    <div>
      <Search style={styles} />
      Contact
    </div>
  )
}

【讨论】:

  • 谢谢你,一直在玩它,我一直收到错误:TypeError: useContext(...) is undefined 但是我没有在这个项目中使用 TypeScript。但是,我在 App.js 文件中使用 useLocation ,而不是在每个单独的组件中,如上所示。有什么想法吗?谢谢
  • @Cal 可能(虽然不确定)BrowserRouter 或 Switch 组件正在提供上下文,因此在使用这些之外的钩子时,它无法找到上下文。还是我误解了这个问题?无论如何,我真的看不出有任何理由将 Search 放在页面组件之外。没有它你最终需要一个页面并不是不可想象的。
猜你喜欢
  • 2020-06-04
  • 2021-01-01
  • 2019-02-07
  • 2017-06-29
  • 1970-01-01
  • 2018-10-18
  • 1970-01-01
  • 2021-06-07
  • 2018-03-18
相关资源
最近更新 更多