React 新手问题 - 如何根据路径使参数为真?

React Newbie Question - How do I make a parameter true depending on the path?

我有一个名为 'selected' 的参数,它突出显示了 css 中边栏上的按钮。不幸的是,我遵循的教程没有说明如何将此参数的状态更改为 true 或 false。我想知道如何为未来的项目做到这一点。

import { Update } from '@mui/icons-material';
import React from 'react'
import { Link } from 'react-router-dom';
import './SidebarRow.css'

function SidebarRow({ selected, title, Icon, linkto }) {
    
    if (title == "Home" && (window.location.pathname == "/"))
    {
        selected = true;
    }
    else if (title == "Trending" && (window.location.pathname == "/trending"))
    {
        selected = true;
    }
    else{
        selected=false;
    }


    return (
        <Link to={`/${linkto}`} >
        <div className= {`sidebarRow ${selected && "selected"}`} >
            <Icon className="sidebarRow_icon"/>
            <h2 className="sidebarRow_title">{title}</h2>
            
        </div>
        </Link>
    )
}

export default SidebarRow;

'if' 语句是我的初学者解决这个问题的方法,它不能正常工作。任何帮助将不胜感激。

您逻辑中的主要问题是您将 selected 作为道具传递,但随后想要更改其值。不应修改道具。在父组件中为 selected 定义正确的值并将其传递给子组件,或者创建一个新变量,例如:

let localSelected = (title == "Home" && (window.location.pathname == "/") || (title == "Trending" && (window.location.pathname == "/trending") ? true : false ;

您可以保留 if 逻辑,但三元运算符看起来更简洁。

我的建议是使用 React Router V6 和 <NavLink> 作为 <Link> 的特殊版本,它将在匹配当前 URL 时向呈现的元素添加样式属性。

<NavLink> 是一种特殊的 <Link>,它知道它是否“活跃”。

https://reactrouter.com/docs/en/v6/api#navlink

除了之前的回答,我建议您阅读 React Router 中的 NavLink 组件。我想你需要的大部分逻辑都包含在里面了。

你的主要代码有问题 - 如果你想访问一些数据而不改变它合理使用道具。但是如果你想访问和更改或编辑来自上层组件的数据,你应该使用 Context context / usecontext in react

虽然我在dark/light模式下遇到这个问题