material-ui和routing有几个按钮。Button它位于内部NavLink- 通过按下按钮,url 改变,一个组件被隐藏,一个新组件出现 - 这里一切都很好。
但是我想为按钮添加“活动”样式,variant如果Button我们在指向Link. 从理论上讲,这应该不难,但它没有到达那里。我在jsfiddle.net上画了一个小例子。
const options = [
{
name: 'Приход',
link: '/income'
},
{
name: 'Расход',
link: '/spend'
},
{
name: 'Статистика',
link: '/statistic'
}
];
class TodoApp extends React.Component {
constructor(props) {
super(props)
this.Router = window.ReactRouterDOM.BrowserRouter
this.Button = window['material-ui'].Button;
this.NavLink = window.ReactRouterDOM.NavLink;
this.Route = window.ReactRouterDOM.Route;
}
render() {
return (
< this.Router >
<div>
{
options.map((opt, i) => (
//Если ссылка активна, то заменить [variant="contained"] на [variant="outlined"]
<this.Button key={i} variant="contained" color="primary">
<this.NavLink to={opt.link} >{opt.name}</this.NavLink>
</this.Button>
))
}
<hr />
<this.Route exact path="/income" component={Income} />
<this.Route path="/spend" component={Spend} />
<this.Route path="/statistic" component={Statistic} />
</div>
</ this.Router>
)
}
}
function Income() {
return (
<div>
<h2>Income</h2>
</div>
);
}
function Spend() {
return (
<div>
<h2>Spend</h2>
</div>
);
}
function Statistic() {
return (
<div>
<h2>Statistic</h2>
</div>
);
}
ReactDOM.render(<TodoApp />, document.querySelector("#app"))
我决定这样做:
PS如果更方便,那就看CodeSandBox
UPD。评论后
与主要的starnitsa对接的头,tk。她
path = /,但什么也没发生,重新制作path了主页/home,这就是它的结果:如果你去,比如说 to
/contacts/12,那么按钮Contacts将采用 styleoutlined,即 你需要的方式。(因此,可以用任何数字/字母/单词等代替 12。)PS CodeSandBox 仍在旧链接下。