How to apply styles to a child class in JSS

牧云@^-^@ 提交于 2019-12-12 18:23:11

问题


I'm using React, Material UI with JSS and React Router.

I'm hooking in to <NavLink> to apply an active class like:

<NavLink to={'/dashboard'} activeClassName={classes.active}
 <button className={classes.btn}>Link</button>
/>

The class is being added fine to the parent, but I'm having an issue applying the style to the child button if it's a class. When targeting the element it works, just not the class.

I've looked into using nested JSS, but this still does not work. Any ideas?

  active: {
    '& .btn': { // This doesn't work
      backgroundColor: '#2A354F'
    },
   '& button': { // This works
      backgroundColor: '#2A354F'
    }  
  }

回答1:


If btn is another class defined via JSS, then you need to refer to it using $btn.

See this part of the JSS documentation.

Here's some sample code that works:

import React from "react";
import ReactDOM from "react-dom";
import { NavLink, BrowserRouter } from "react-router-dom";
import { withStyles } from "@material-ui/core/styles";

const styles = {
  btn: {},
  active: {
    "& $btn": {
      backgroundColor: "#2A354F",
      color: "#fff"
    }
  }
};
function App(props) {
  return (
    <BrowserRouter>
      <div className="App">
        <NavLink to="/" activeClassName={props.classes.active}>
          <button className={props.classes.btn}>Link</button>
        </NavLink>
      </div>
    </BrowserRouter>
  );
}
const StyledApp = withStyles(styles)(App);
const rootElement = document.getElementById("root");
ReactDOM.render(<StyledApp />, rootElement);




回答2:


It does not work due to class name ".btn" because the root class "active" after rendering of React will not have the same class name and it cannot found out it.

just set {classes.btn}

<button className={classes.btn}>Link</button>


来源:https://stackoverflow.com/questions/54184180/how-to-apply-styles-to-a-child-class-in-jss

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!