如何在JSS中将样式应用于子类 [英] How to apply styles to a child class in JSS
问题描述
我正在使用React,带有JSS的Material UI和React Router.
I'm using React, Material UI with JSS and React Router.
我正在连接<NavLink>
来应用活动类,例如:
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.
我已经研究过使用嵌套的JSS ,但这仍然行不通.有任何想法吗?
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'
}
}
推荐答案
如果btn
是通过JSS定义的另一个类,则需要使用$btn
引用它.
If btn
is another class defined via JSS, then you need to refer to it using $btn
.
请参见以下一些有效的示例代码:
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);
这篇关于如何在JSS中将样式应用于子类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!