请帮助我不知道如何在反应中做到这一点 所以我有三个按钮,我需要这样做,这样当您单击一个按钮时,其他按钮的状态就会设置回 false
这是代码
`import votingimg from '../assets/header-assets/voting-img.png'
import galleryimg from '../assets/header-assets/gallery-img.png'
import breedsimg from '../assets/header-assets/breeds-img.png'
import { useState } from 'react'
import votingimg from '../assets/header-assets/voting-img.png'
import galleryimg from '../assets/header-assets/gallery-img.png'
import breedsimg from '../assets/header-assets/breeds-img.png'
import { useState } from 'react'
const Actions = () => {
const [votingActive, setVotingActive] = useState(false)
const [galleryActive, setGalleryActive] = useState(false)
const [breedsActive, setBreedsActive] = useState(false)
const votingOnClick = () => {
setVotingActive(true)
setGalleryActive(false)
setBreedsActive(false)
}
const galleryOnClick = () => {
setVotingActive(false)
setGalleryActive(true)
setBreedsActive(false)
}
const breedsOnClick = () => {
setVotingActive(false)
setVotingActive(false)
setBreedsActive(true)
}
// im sorry about this code
return (
<div className='action__wrapper'>
<div className="action">
<div className='voting__bg'>
<img className='action__img' src={votingimg} alt="voting" />
</div>
<button className={votingActive ? 'active__btn' : 'action__btn'}
onClick={votingOnClick}
>voting</button>
</div>
<div className="action">
<div className="breeds__bg">
<img className='action__img-breeds' src={breedsimg} alt="breeds" />
</div>
<button className={breedsActive ? 'active__btn' : 'action__btn'}
onClick={breedsOnClick}>breeds</button>
</div>
<div className="action">
<div className="gallery__bg">
<img className='action__img-gallery' src={galleryimg} alt="gallery" />
</div>
<button className={galleryActive ? 'active__btn' : 'action__btn'}
onClick={galleryOnClick}>gallery</button>
</div>
{/* each of this could be just a reusable component */}
{/* need to change export to svg for netter quality */}
</div>
)
}
export default Actions
我知道我的解决方案很糟糕,但它有效,我发现的只是普通js或类组件react的解决方案
为什么不只使用一个 useState 呢?例如:
const [btnsState, setBtnsState] = useState({votingActive: false,galleryActive:false, breedsActive: false })
所以你可以定义一个函数,将所有状态更改为 false,然后将你想要的状态设置为 true,类似这样:
// the key parameter in the function is the key you want to change in the object to true
const changeState = (key) = > {
// copy the current state
const stateCopy = structuredClone(btnsState)
// loop through the object
for (const prop in copy){
// change keys different from the one you want to be true to false
if(prop !== key){
copy[prop] = false
}
}
//change the key you want to be true to true
stateCopy[key] = true
// set the new state
setBtnsState(stateCopy)
}
当然还有其他方法可以做到这一点,但这一个有点简单,也可以改进。