选择项目时如何更改菜单的背景颜色?

我仍然是 React JS 的初学者,我对示例菜单有疑问。

我有一个菜单,我需要在用户单击菜单时更改背景,以便用户知道他在哪个页面上。我已经做了几次测试,但我仍然无法做到。

这是我放在 codesandbox 中的代码:https ://codesandbox.io/s/patient-resonance-6pwjh?file=/src/index.js

有人能帮我吗?


凤凰求蛊
浏览 81回答 2
2回答

喵喔喔

这是工作示例:https://codesandbox.io/s/patient-cherry-tpf50注意:您需要"react-router-dom": "5.2.0"在package.json文件中添加此依赖项。反应代码:import React from "react";import { BrowserRouter as Router, NavLink } from "react-router-dom";import "./styles.css";export default function App() {&nbsp; return (&nbsp; &nbsp; <Router>&nbsp; &nbsp; &nbsp; <div className="App">&nbsp; &nbsp; &nbsp; &nbsp; <div className="topnav">&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <NavLink to="/home" activeClassName="active">&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Home&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; </NavLink>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <NavLink to="/news" activeClassName="active">&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; News&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; </NavLink>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <NavLink to="/contact" activeClassName="active">&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Contact&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; </NavLink>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <NavLink to="/about" activeClassName="active">&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; About&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; </NavLink>&nbsp; &nbsp; &nbsp; &nbsp; </div>&nbsp; &nbsp; &nbsp; </div>&nbsp; &nbsp; </Router>&nbsp; );}款式:.App {&nbsp; font-family: sans-serif;&nbsp; text-align: center;}.topnav {&nbsp; overflow: hidden;&nbsp; background-color: #333;}a {&nbsp; float: left;&nbsp; color: #f2f2f2;&nbsp; text-align: center;&nbsp; padding: 14px 16px;&nbsp; text-decoration: none;&nbsp; font-size: 17px;}a.active {&nbsp; background-color: #1144ff;&nbsp; color: #ffffff;}a:hover {&nbsp; background-color: #ddd;&nbsp; color: black;}

慕运维8079593

我使用样式化组件管理了类似的东西。它允许您根据道具设置组件样式。我有一个包含食谱的页面,顶部有一个类别栏,其中包含用户可以过滤食谱的蛋白质列表。我创建了一个 activeCategory 状态,默认情况下将其设置为“全部”,但当用户单击它时,它会更改为选择的任何蛋白质。我只是将该状态作为道具传递给 categoryBar 组件,并在它是活动类别时更改所选蛋白质的背景颜色。您可以在 CategoryBar.js 的第 12 行中明白我的意思。如果您想查看状态,Picker.js 是父组件。https://github.com/Taouen/gobble/tree/master/src/components
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript