【问题标题】:Is it possible to activate a css class that effect the html tag depending on the route?是否可以根据路由激活影响 html 标记的 css 类?
【发布时间】:2019-06-11 10:04:00
【问题描述】:

我正在创建一个 在主页(“/”)中应该有的反应站点:

    html{
        overflow: hidden;
    }

但是当我移动到 css 处于活动状态的任何其他页面(“/something”)时
(那个 css 在 home.css 中,只在 home.js 中链接)

以下所有代码都是 App.js:

    const App = () => {
      return (
        <Router>
          <Switch>
            <Route exact path="/" component={Home} />
            <Route path="/page" component={Page} />
          </Switch>
        </Router>
      );
    }

Home.js:

    import './Home.css';

Home.css:

    @media (min-width: 1024px) {
        html {
            overflow: hidden;
        }
    }

Page.js:

    import './Page.css';

Page.css:

    (nothing)

我希望页面“/”使用 Home.css 的 css 而其他页面不使用 Home.css

【问题讨论】:

  • 你能查一下this.props.location.pathname吗?
  • 我们可以配置 Webpack 和 CSS Loader 来解析 CSS 并加载到浏览器中。我们可以为一个组件编写 CSS 并确保它不会泄漏到其他组件中。您还可以确信向应用程序添加新组件不会干扰系统上的任何其他组件。看看这篇文章:javascriptplayground.com/css-modules-webpack-react
  • 看看这部分{ test: /\.css$/, loader: 'style-loader' }, { test: /\.css$/, loader: 'css-loader', query: { modules: true, localIdentName: '[name]__[local]___[hash:base64:5]' } }modules: true 开启CSS模块模式
  • CSS 模块只是一种自动命名 css 的方法,这样您的模块样式就不会相互干扰。对这个问题一点帮助都没有。

标签: javascript css reactjs react-router


【解决方案1】:

您的 css 导入不是动态添加和删除的,它们都被隐藏起来并注入到 &lt;head&gt; 或在您构建捆绑包时捆绑到单个 css 文件中。

在导航时向&lt;html&gt; 标签添加或删除样式是可能的,但会很麻烦。重新构建应用程序会更容易(也更明智),以便您可以将 overflow:hidden 应用于某些页面上的包含元素,但不能应用于其他页面。

【讨论】:

    【解决方案2】:

    css 无法实现,但可以使用如下内联样式:

    import React from "react";
    import ReactDOM from "react-dom";
    
    import "./styles.css";
    
    function Home() {
      return (
        <div className="Home" style={{overflow: window.innerWidth >= 1024 ? 'hidden' : 'initial'}}>
          <h1>Home </h1>
        </div>
      );
    }
    
    function Page() {
      return (
        <div className="Page" style={{overflow: 'initial'}}>
          <h1>Page</h1>
        </div>
      );
    }

    【讨论】:

      猜你喜欢
      • 2021-11-22
      • 2023-01-11
      • 1970-01-01
      • 2011-11-19
      • 1970-01-01
      • 2016-12-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多