Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

reactjs - How to apply styles to a child class in JSS

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'
    }  
  }
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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);

Edit vknyr3vql


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...