React点击激活按钮



有四个按钮。您当前可以一键移动链接。但是,您需要双击按钮来激活按钮的颜色。

我想通过点击激活链接和按钮。有可能得到一些帮助吗?

边栏.js

const [selectBtn, setSelectBtn] = useState();
{SETTING_BAR_ICON.map(data => {
return (
<SidebarIcon
key={data.id}
src={data.img}
select={data.select}
link={data.link}
handleChangeBtnColor={() => 
setSelectBtn(data.id)}
isSelectBtn={selectBtn === data.id}
/>
);
})}

边栏图标.js

<SidebarIconContainer>
{isSelectBtn ? (
<ImgBackground>
<ImgSelect src={select} />
<ImgText>{link}</ImgText>
</ImgBackground>
) : (
<Link to={`/${link}`}>
<ImgFormat src={src} onClick=. 
{handleChangeBtnColor} />
</Link>
)}
</SidebarIconContainer>

第一个问题是永远不要关闭SidebarIconhandleChangeBtnColor属性中的函数花括号。在/>之前需要一个}。您还需要将里面的两个方法封装在花括号中。当你使用箭头函数时,总是使用花括号,谎言是:

const doSomething = () => {
...
}

除非你只有一件事要返回里面,否则你可以省略这样的花括号:

// shorthand
const doSomething = () => doAThing()
const getSomething = () => 'thing'
// same as this
const doSomething = () => {
return doAThing()
}
const getSomething = () => {
return 'thing'
}
// if you go to the next line you should use parenthesis
const doSomething = () => (
doAThing()
)

但我认为这不会解决问题。与其使用Link标签,不如使用useNavigation钩子并更改handleChange...函数中的路径。这样的东西:

import { useNavigate } from 'react-router-dom'
const navigate = useNavigate()
return (
<SidebarIcon
...
handleChangeBtnColor={(link) => {
setSelectBtn(data.id)
isSelectBtn={selectBtn === data.id}
navigate(`/${link}`)
}}
/>
)
<DivStyledLikeYourOtherLinks onClick={() => handleChangeBtnColor(link)} />

最新更新