【问题标题】:Apply CSS only when for specific route仅在针对特定路线时应用 CSS
【发布时间】:2017-10-20 17:41:31
【问题描述】:

如何仅在提供特定路线时应用 CSS 规则?

import React from 'react'
import ReactDOM from 'react-dom'
import registerServiceWorker from './registerServiceWorker'
import './styles/index.css'
import {
  Route, Switch, BrowserRouter as Router
} from 'react-router-dom'
import App from './components/App'
import Life from './components/Life'

ReactDOM.render(
    <Router>
        <Switch>
            <Route exact path="/life" component={Life} />
            <Route path="/" component={App} />
        </Switch>
    </Router>
    , document.getElementById('root'));
registerServiceWorker();

./styles/index.css 中,我有一些body 的规则,例如,我只想在路由'/life' 提供服务时覆盖这些规则。我怎样才能做到这一点?

【问题讨论】:

    标签: reactjs react-router jsx


    【解决方案1】:

    您可以在需要时根据当前路由添加特定的 css 类:

    .tagClass {
      width: 1200px;
    }
    
    class App extends Component {
      render() {
        let tagPath = '/life' == this.context.location.pathname
        return (
          <div className={tagPath?'tagClass':''} />
        )
      }
    }
    
    App.contextTypes = {
        router: React.PropTypes.object,
        location: React.PropTypes.object
    }
    

    编辑:根据评论问题

    您可以为 App 组件指定监听器:

    componentDidMount() {
        this.context.router.getLocation().addChangeListener(listener);
    }
    componentWillUnmount() {
        this.context.router.getLocation().removeChangeListener(listener);
    }
    

    或每个路由处理程序:

    function handler() {
      do something;
    }
    
    <Route path='/' component={App}>
      <Route path="foo" component={Foo} onEnter={handler}/>
      <Route path="life" component={Life} onEnter={handler}/>
    </Route>
    

    【讨论】:

    • 谢谢,但我想更改不在组件中而是在公共文件夹中的正文。
    • 据我所知,react 无法访问正文。但是你可以用纯js手动完成。
    【解决方案2】:

    所以,显然你可以在 React 组件中使用 require()。 这意味着您可以在您的函数/类内部或直接在 import 语句下的组件外部执行类似的操作:

    if (window?.location.pathname === '/life')
        require('./styles/index.css')
    

    我不知道是否应该这样做,这似乎有点违法,但它确实有效。

    【讨论】:

    • 感谢@drinking-code 你在这里救了我的命
    【解决方案3】:

    可以在index.html文件的script标签中添加setInterval。

    像这样:

     setInterval(()=> {
    if(location == '/'){
    ..function
    }
    else if(location == '/about'){
    ..function
    }
    }, 1)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-03-20
      • 1970-01-01
      • 1970-01-01
      • 2011-10-11
      • 1970-01-01
      相关资源
      最近更新 更多