如何在React.js的Styled Components中单独修改点击的同类型组件标签文本颜色
Optimizing Your React + Styled Components Tab Selection
Hey there! Your current implementation gets the job done, but it’s not very scalable—imagine having to add 5 more tabs later, you’d have to update the state array, write new handler functions, and adjust every component’s style prop. Let’s simplify this with a more maintainable approach:
Core Improvements
- Instead of storing an array of colors, track just the active tab identifier (like "A", "B", or "C") in state. This keeps state lean and easy to update.
- Use Styled Components' built-in props to dynamically apply styles, rather than passing inline styles.
- Reuse a single click handler instead of writing separate functions for each tab.
Refactored Code
import { useState } from "react"; import styled from "styled-components"; function Nav() { // Track which tab is active (null means none selected initially) const [activeItem, setActiveItem] = useState(null); // Reusable click handler: pass the item identifier when clicked const handleItemClick = (item) => { setActiveItem(item); }; return ( <Container> <List active={activeItem === "A"} onClick={() => handleItemClick("A")} > A </List> <List active={activeItem === "B"} onClick={() => handleItemClick("B")} > B </List> <List active={activeItem === "C"} onClick={() => handleItemClick("C")} > C </List> </Container> ); } // Update the styled component to use the `active` prop for color const List = styled.li` list-style-type: none; display: inline; padding: 0 10px; border-left: 1px solid black; cursor: pointer; outline: 0 none; // Dynamically set color based on the active prop color: ${props => props.active ? "orange" : "black"}; `; const Container = styled.ul` /* Add any container styles here if needed */ `;
Even Better: Iterate Over an Array (For Scalability)
If you think you might add more tabs later, store your tab labels in an array and render them dynamically. This cuts down on repetitive code:
function Nav() { const [activeItem, setActiveItem] = useState(null); const handleItemClick = (item) => setActiveItem(item); // Define your tabs in an array const tabs = ["A", "B", "C"]; return ( <Container> {tabs.map(tab => ( <List key={tab} active={activeItem === tab} onClick={() => handleItemClick(tab)} > {tab} </List> ))} </Container> ); }
Why This Works Better
- Scalability: Adding a new tab only requires updating the
tabsarray (no state or handler changes needed). - Cleaner State: Instead of managing an array of colors, we track a single value—much easier to debug and maintain.
- Styled Components Best Practice: Leveraging props for dynamic styles keeps your styling logic centralized in the styled component, rather than scattered in inline styles.
内容的提问来源于stack exchange,提问作者Junrae Kim
相关产品推荐
相关产品推荐

