我有一個名為'selected'的引數,它突出顯示css側邊欄上的按鈕。不幸的是,我遵循的教程沒有顯示如何將此引數的狀態更改為真或假。我想知道如何為未來的專案做到這一點。
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' 陳述句是我對這個問題的初學者,它不能正常作業。任何幫助將非常感激。
uj5u.com熱心網友回復:
您邏輯中的主要問題是您selected作為道具傳遞但隨后想要更改其值。不應修改道具。在父組件中定義適當的值selected并將其傳遞給子組件,或者創建一個新變數,例如:
let localSelected = (title == "Home" && (window.location.pathname == "/") || (title == "Trending" && (window.location.pathname == "/trending") ? true : false ;
您可以保留 if 邏輯,但三元運算子看起來更干凈。
uj5u.com熱心網友回復:
我的建議是使用 React Router V6<NavLink>作為一個特殊版本,<Link>當它與當前 URL 匹配時,它將向呈現的元素添加樣式屬性。
A<NavLink>是一種特殊的型別,<Link>它知道它是否“活躍”。
https://reactrouter.com/docs/en/v6/api#navlink
uj5u.com熱心網友回復:
除了上一個答案,我建議您閱讀 React Router 中的 NavLink 組件。我認為您需要的大部分邏輯都包含在其中。
uj5u.com熱心網友回復:
您的主要代碼有問題 - 如果您想訪問某些資料而不更改使用 props 的合理性。但是如果你想訪問和更改或編輯來自上層組件的資料,你應該 在 react 中使用 Context context / usecontext
雖然我在暗/亮模式下遇到了這個問題
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/411658.html
標籤:
上一篇:當狀態改變時反應切換主體類
