TIL
TIL 221119 스타일드 컴포넌트 props에 타입 정해주기
2021bong
2022. 11. 20. 00:29
state를 이용해서 스타일링을 다르게 주고 싶어서 스타일드 컴포넌트에 props를 넘겨 줬다.
const BirthdayCake = () => {
const [btnSize, setBtnSize] = useState(false);
const [candleFlame, setCandleFlame] = useState(true);
const [flameUrl, setFlameUrl] = useState('images/flame1.png');
useEffect(() => {
if (!candleFlame) {
setBtnSize(false);
setFlameUrl('');
return;
}
const btnSizeTime = setInterval(() => {
setBtnSize((prev) => !prev);
}, 700);
const flameUrlTime = setInterval(() => {
setFlameUrl(url[Math.floor(Math.random() * url.length)]);
}, 300);
return () => {
clearInterval(btnSizeTime);
clearInterval(flameUrlTime);
};
}, [candleFlame]);
const handleCandleFlame = () => {
setCandleFlame(false);
};
return (
<Cake>
<CandleFlame flameUrl={flameUrl}>
{!candleFlame && (
<h1>
<br />
💕 친구야 💕
<br />
생일 축하해 🎉
</h1>
)}
<BlowBtn btnSize={btnSize} onClick={handleCandleFlame}>
{!candleFlame ? '생일 축하해' : '촛불 끄기'}
</BlowBtn>
</CandleFlame>
</Cake>
);
};
export default BirthdayCake;
const BlowBtn = styled.button`
...
box-shadow: 0 4px 6px rgba(50, 50, 93, 0.3), 0 1px 3px rgba(0, 0, 0, 0.1);
transform: ${({ btnSize }) => (btnSize ? 'scale(1)' : 'scale(1.2)')};
transition: 0.3s;
...
`;
const CandleFlame = styled.div`
width: inherit;
height: inherit;
padding: 80px;
background: ${({ flameUrl }) => `no-repeat bottom/150% url(${flameUrl})`};
`;
그런데 빨간줄이 좍좍 뜨는게 아닌가....😨 또.. 왜요......🥺 찾아보니 스타일드 컴포넌트에도 타입을 정해줘야했다.
타입을 선언해주고 스타일드 컴포넌트에 타입을 정해주면 된다.
interface BtnSize {
btnSize: boolean;
}
interface FlameUrl {
flameUrl: string;
}
const BlowBtn = styled.button<BtnSize>`
...
box-shadow: 0 4px 6px rgba(50, 50, 93, 0.3), 0 1px 3px rgba(0, 0, 0, 0.1);
transform: ${({ btnSize }) => (btnSize ? 'scale(1)' : 'scale(1.2)')};
transition: 0.3s;
...
`;
const CandleFlame = styled.div<FlameUrl>`
width: inherit;
height: inherit;
padding: 80px;
background: ${({ flameUrl }) => `no-repeat bottom/150% url(${flameUrl})`};
`;
넘겨주는 props가 하나라면 이렇게 할 수도 있다.
${({ props이름 }: { props이름 : 타입 }) => ...
const setColor = () => {
if (textValue.length < 100) {
return '#00B388';
} else if (textValue.length < 120) {
return '#FAB922';
} else {
return '#FA3270';
}
};
...
<NoticeCurcle noticeColor={setColor()} />
...
const NoticeCurcle = styled.span`
display: inline-block;
width: 0.5rem;
height: 0.5rem;
border-radius: 50%;
background-color: ${({ noticeColor }: { noticeColor: string }) =>
noticeColor};
transform: translateY(-2px);
`;
728x90