I have 2 spans and state for them:
const Sorter = () => {
const [sorterTabs, setSorterTabs] = useState([
{id:'The cheapest', isActive: false },
{id:'The fastest', isActive: false }
])
const handleSorterClick = ({ target }) => {
const newSorterTabs = [...sorterTabs]
newSorterTabs.forEach((item) => {
if (item.id === target.getAttribute('name')) {
item.isActive = !item.isActive
}
})
setSorterTabs(newSorterTabs)
}
return (
<>
{sorterTabs.map((item) =>
<SorterSpan
key={item.id}
onClick={handleSorterClick}
name={item.id}
className={item.isActive ? 'active' : ''}
/>
)}
</>
)
}
const SorterSpan = ({name, onClick, className}) => {
return (
<span
onClick={onClick}
className={className}
name={name}
>
{name}
</span>
)
}
I understand how I can change isActive
property for each of span. What I need is if I click one span, and it's property isActive
becomes true the other span isActive
needs to become false and the same for the second span. How to do it properly in handleSorterClick
function?
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…