简体   繁体   English

React CSS 模块 - 一些 CSS 未应用(对于 NavLink 组件设置的“活动”class)

[英]React CSS Modules - Some CSS is not applied (for 'active' class set by NavLink component)

The CSS for my active class does not seem to get applied on the rendered component, even though the rest of the CSS is actually applied.我的active class的 CSS 似乎没有应用到渲染组件上,即使实际应用了 CSS 的 rest。 The CSS is applied using CSS modules.使用 CSS 模块应用 CSS。 Since the NavLink component of react-router-dom package sets the class to active, I have selected the active class in the CSS file, but for some reason everything gets applied to the rendered HTML but that specific selection.由于 react-router-dom package 的NavLink组件将 class 设置为活动状态,因此我在 CSS 文件中选择了活动的 class,但由于某种原因,所有内容都应用于呈现的 HTML,但该特定选择除外。

The render() method of the React component : React 组件render()方法

render () {
        return (
            <Fragment>
                <nav className={CSSModule.Nav}>
                     <ul>
                         <li><NavLink to="/" exact>Home</NavLink></li>
                         <li><NavLink to={{
                             pathname: "/new-post",
                             hash: "#submit",
                             search: "?quick-submit"
                         }}>New Post</NavLink></li>
                     </ul>
                 </nav>
            
            <Route 
                path={["/", "/home"]} 
                exact 
                component={Posts} />

            <Route 
                path="/new-post"
                exact 
                component={NewPost} />

            </Fragment>
        );
    }

The CSS code: CSS代码:

.Nav {
    box-sizing: border-box;
    padding: 20px;
}

.Nav ul {
    list-style: none;
    display: flex;
    justify-content: space-evenly;
    background-color: burlywood;
    padding: 10px;
}

.Nav ul a {
    color: black;
    text-decoration: none;
}

.Nav ul a:active {
    color: white;
}

.Nav ul a:hover,
.Nav ul a.active {
    border-bottom: 1px solid black;
}

Here is a codesandbox sample. 是一个codeandbox示例。

After some more detailed research, it would seem like CSS Modules somehow block the styling for the active class from getting applied.经过一些更详细的研究,似乎 CSS 模块以某种方式阻止应用活动 class 的样式。

you should remove all activeClassName="my-active" in app.js and add this in styles.module.css您应该删除 app.js 中的所有activeClassName="my-active"并将其添加到styles.module.css

a[class="active"] {
  border-bottom: 1px solid black !important;
}

otherwise you should set activeClassName={CSSModule.active} for each NavLink and be sure that the .active is defined in your style否则你应该为每个NavLink设置activeClassName={CSSModule.active}并确保.active在你的样式中定义

Just change your selector to my-active instead of .active :只需将您的选择器更改为my-active而不是.active

.Nav ul a:hover,
.Nav ul a.my-active {
  border-bottom: 1px solid black !important;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM