如何在反应、样式化的组件中使用字体真棒图标更改单选按钮的颜色
Posted
技术标签:
【中文标题】如何在反应、样式化的组件中使用字体真棒图标更改单选按钮的颜色【英文标题】:How to change the color of radio button with font awesome icon in react, styled components 【发布时间】:2022-01-15 20:22:30 【问题描述】:我只想改变点击的图标颜色,但点击时整个图标的颜色会改变。 我知道这基本上是因为 useState 没有分配给每个点击事件,但我被困在这里,不知道如何处理。
const moods = [
icon: faGrinStars, mood: 'super' ,
icon: faSmile, mood: 'good' ,
icon: faMeh, mood: 'soso' ,
icon: faFrown, mood: 'bad' ,
icon: faAngry, mood: 'angry' ,
];
const [clicked, setClicked] = useState(false);
const handleClick = () =>
setClicked(!clicked);
;
return (
<StyledDiv>
moods.map((mood) => (
<div key=mood.mood>
<input
type='radio'
name='mood'
id=mood.mood
onClick=handleClick
/>
<label htmlFor=mood.mood>
<FontAwesomeIcon
icon=mood.icon
size='2x'
style=clicked ? color: 'red' : color: '#5e5c5a'
/>
</label>
</div>
))
</StyledDiv>
);
;
const StyledDiv = styled.div`
$( theme ) =>
const colors = theme;
return css`
input
display: none;
`;
`;
export default MoodIcons;
【问题讨论】:
【参考方案1】:使用数组保存所有点击按钮的状态。 像这样的:
const moods = [
icon: faGrinStars, mood: 'super' ,
icon: faSmile, mood: 'good' ,
icon: faMeh, mood: 'soso' ,
icon: faFrown, mood: 'bad' ,
icon: faAngry, mood: 'angry' ,
];
const [clicked, setClicked] = useState([false, false, false, false, false]);
const handleClick = (i) =>
setClicked(prevState =>
const nextStaet = [...prevState];
nextStaet[i] = !nextStaet[i];
return nextStaet;
);
;
return (
<StyledDiv>
moods.map((mood, index) => (
<div key=mood.mood>
<input
type='radio'
name='mood'
id=mood.mood
onClick=() => handleClick(index)
/>
<label htmlFor=mood.mood>
<FontAwesomeIcon
icon=mood.icon
size='2x'
style=clicked[clicked] ? color: 'red' : color: '#5e5c5a'
/>
</label>
</div>
))
</StyledDiv>
);
;
const StyledDiv = styled.div`
$( theme ) =>
const colors = theme;
return css`
input
display: none;
`;
`;
export default MoodIcons;
【讨论】:
以上是关于如何在反应、样式化的组件中使用字体真棒图标更改单选按钮的颜色的主要内容,如果未能解决你的问题,请参考以下文章