【问题标题】:change color to a functional component将颜色更改为功能组件
【发布时间】:2021-11-06 21:37:30
【问题描述】:

我需要把header组件的h1文本颜色改成黑色,但是home不行,只给其他页面,我试过inline style但是不行,有什么解决办法吗?

    <Router>

      <div className="app">

        <Switch>

          <Route path='/portraits'>
            <Header />
            <Portraits />
            <Footer />
          </Route>

          <Route path='/contact'>
            <Header />
            <Contact />
            <Footer />
          </Route>

          <Route path='/'>
            <Header />
            <Home />
          </Route>

        </Switch>

      </div>

    </Router>

标题组件,我使用引导程序作为下拉菜单

<nav>
            <Link to='/' className="title">
                <h1>Ioana Savin</h1>
            </Link>

            <div className="head">

            <DropdownButton title="Portfolio" className='button'>
                
                      
                    <Dropdown.Item href='/fashion'>Fashion</Dropdown.Item>
                
                    <Dropdown.Item href='/portraits'>Portraits</Dropdown.Item>
                
                    <Dropdown.Item href='/bnw'>BnW</Dropdown.Item>
                
                    <Dropdown.Item href='/analogue'>Analogue</Dropdown.Item>
                
                    <Dropdown.Item href='/clienti'>Clienti</Dropdown.Item>
                

            </DropdownButton>
            
            <Link to='/portfolio' className="link">   
            <DropdownButton title="Contact" className='button' />     
            </Link>
            
            </div>
        </nav>

【问题讨论】:

  • 请显示 Header 组件

标签: reactjs components react-functional-component


【解决方案1】:

我看到了&lt;Router&gt;,所以我认为您正在使用react-router。 您可以在 Header 组件中检查您正在使用的路线:

import { useLocation } from 'react-router-dom';

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

  return (
    <>
     <h1 style={location.pathname !== 'home' ? {color: "black"} : {}}>Title</h1>
     [... other components]
    </>
  )
}

(显然用你主页的路径名替换'home')

【讨论】:

    【解决方案2】:

    您可以使用道具来控制它:

    <Route path='/'>
      <Header isHomeScreen />
      <Home />
    </Route>
    
    <h1 style={!isHomeScreen ? {color: "black"} : {}}>Ioana Savin</h1>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-03-24
      • 2022-11-30
      • 2020-06-22
      • 2021-03-02
      • 2021-06-17
      • 1970-01-01
      • 2020-12-21
      • 1970-01-01
      相关资源
      最近更新 更多