【问题标题】:How to change props in a Material UI component according to URL?如何根据 URL 更改 Material UI 组件中的道具?
【发布时间】:2020-08-07 17:49:47
【问题描述】:

在 Next.js 网站的主页 (index.js) 中,我有一个 AppBar 材质 UI 组件,带有道具 position="fixed"

在所有其他页面中,我想将道具设置为position="static"

我可以制作 2 个组件,Header1(仅在主页上呈现)和 Header2(在所有其他页面上呈现),并为每个 AppBar 组件分配不同的道具,但我想有更好的方法。

如何根据 URL 动态改变组件中的 CSS 类或道具?

【问题讨论】:

    标签: reactjs material-ui next.js


    【解决方案1】:

    对 Next.js 不太熟悉,但如果您使用位置,它应该可以工作,例如 React 中的 window.location 或组件内的 props.location。快速搜索 Next.js 会建议类似这样的内容

    import { useRouter } from 'next/router'
    
    function YourFunction({ children, url }) {
      const router = useRouter()
      const style = {
        position: router.pathname === url ? 'fixed' : 'static',
      }
    
    (...)
    
    }
    
    ``
    

    【讨论】:

      猜你喜欢
      • 2019-02-27
      • 2020-02-05
      • 1970-01-01
      • 2021-10-20
      • 2016-07-29
      • 1970-01-01
      • 2018-02-19
      • 2018-11-24
      • 2021-10-02
      相关资源
      最近更新 更多