react-tutorial
react-tutorial copied to clipboard
3. styled-components · GitBook
안녕하세요. 10. Styled-components 버튼 사이즈 조정하기 영상에서 6:50초부터 9:20초까지 검은영상만 나오네요.
@vonprios 감사합니다 :) 패캠쪽에 전달 드리도록 하겠습니다. 내용이 짤린건 아니고.. 6:50이 영상의 끝입니다. 뒤에 불필요한 검정영상이 추가된것같네요~
모달 만들기 바로 직전 코드인데요, 버튼들 중에서 fullWidth
prop을 가지지 않은 버튼 한테도 margin-left: 0;
이 적용됩니다... 선생님 강의 보면서 따라 하다가 뭐가 다른지 모르겠어서, 쌤이 올려준 코드를 복붙해서 실행시켜 봤는데 똑같이 적용되네용... ㅜㅜ margin-top: 1rem;
이 부분은 확실이 fullWidth
prop이 있는 코드만 영향 받는게 맞는데 margin-left: 0;
은 왜 모든 버튼에 적용되는지 모르겠습니다... 저 부분 들만 주석처리 해서 실행을 다 해봤거든요.. 호시 저처럼 되시는 분, 혹은 이유를 아시는 분 도움 부탁드리겠습니당...
// Button.js
const fullWidthStyle = css`
${props =>
props.fullWidth &&
css`
width: 100%;
justify-content: center;
& + & {
/*margin-left: 0;*/
margin-top: 1rem;
}
`}
`;
& + & selector를 styled-components에서 사용할 경우, 이유는 모르겠지만 브라우저를 열어보시면 모든 버튼에 동일하게 부여된 classname에 margin값이 적용됩니다. 그래서 최초 의도한 & + &의 의미인 바로 옆의 버튼에만 마진값을 적용하라는 의미는 퇴색되고 모든 버튼에 동일한 마진값이 적용되는 것이죠. 저는 & + & 대신 &:not(:first-child) selector를 사용함으로써 해결했습니다. 참고하세요!
@YunhwanJung 설명 정말 감사합니다 ㅎㅎㅎㅎ 진짜 도움 되었어요!! 👍
안녕하세요?? 어제부터 yarn start 할 때, 문제가 계속 발생하는데 해결하기 어려운 것 같습니다. You gave us a visitor for the node type StaticBlock but it's not a valid type이라는 에러메세지가 뜨는 데 인터넷에 자세하게 안나와 있네요 ㅠㅠ 혹시 문제를 해결할 수 있는 방안이 있을까요?
Error: You gave us a visitor for the node type StaticBlock but it's not a valid type
at verify (E:\git\prac_style\node_modules@babel\traverse\lib\visitors.js:112:13)
at explode (E:\git\prac_style\node_modules@babel\traverse\lib\visitors.js:34:3)
at Object.merge (E:\git\prac_style\node_modules@babel\traverse\lib\visitors.js:147:5)
at Object.
at Module._compile (internal/modules/cjs/loader.js:1063:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1092:10)
at Module.load (internal/modules/cjs/loader.js:928:32)
at Function.Module._load (internal/modules/cjs/loader.js:769:14)
at Module.require (internal/modules/cjs/loader.js:952:19)
at require (internal/modules/cjs/helpers.js:88:18)
error Command failed with exit code 1.
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.
& + & 를 쓸때, 모두 fullWidth css 가 적용되는 현상은 styled-components 5.1.1 까지는 발생하지 않았는데, 5.2.0 부터 발생하고 있습니다. 5.2.1에서도 수정되지 않아서 실습하시는 분들은. @YunhwanJung 님이 제안주신 방법으로 바꾸어서 실습하시면 정상작동합니다.
sizeStyle에서 다음과 같은 코딩은 되지 않더라구요... 왜 그런지 모르겠네요..
const sizeStyle = css ${(props) => { if (props.size === 'large') { return css
height: 3rem;
font-size: 1.25rem;
; } else if (props.size === 'medium') { return css
height: 2.25rem;
font-size: 1rem
; } else if (props.size === 'small') { return css
height: 2.25rem;
font-size: 1rem
; } }}
;
다시...
const sizeStyle = css`
${(props) => {
if (props.size === 'large') {
return css`
height: 3rem;
font-size: 1.25rem;
`;
}
else if (props.size === 'medium') {
return css`
height: 2.25rem;
font-size: 1rem
`;
}
else if (props.size === 'small') {
return css`
height: 2.25rem;
font-size: 1rem
`;
}
}}
`;
@woorara7 혹시 저와 비슷한 상황인 것 같아서 말씀드려요!
저도 props
로 size
를 받아오는데 npm start
를 해보면 계속 TypeError: Cannot read property height of undefined
를 반환하더라고요..
아마 @woorara7 님께서도 저처럼 App.js
에서 <Button>
을 사용할때, 모든 <Button>
에 size
를 지정해주시지 않은 것 같아요.
const Button = ({ children, size, ...rest }) => {
console.log(size);
return (
<StyledButton onClick={onClick} size={size} {...rest}>
{children}
</StyledButton>
);
};
return 이전에 console.log
를 사용해보시면, size
를 설정해준 <Button>
은 사이즈 값을 반환하고, 그냥 size
없이 <Button>
만 설정된 애들은 undefined
를 반환합니다.
해결 : 이미 나와있는데 제가 스스로 해보려다보니 놓쳐서요.. Button.defaultProps
로 size
를 설정해두면 됩니다!
Button.defaultProps = {
size: "medium",
};
const fullWidthStyle = css`
${props =>
props.fullWidth &&
css`
width: 100%;
justify-content: center;
& + & {
margin-left: 0;
margin-top: 1rem;
}
`}
`;
Dialog
부분을 따라하는데 2개 이상의 Button
컴포넌트를 호출할 때 fullWidth
을 넘기지 않아서 콘솔에 찍었을 때 undefined
값이 뜨는데 주석으로 1을 써놓은 코드들은 적용 안되고 2를 써놓은 코드들은 적용이 됩니다. 이에 대한 이유를 알 수 있을까요? 제가 작성한 코드 아래와 같아요
const fullWidthStyle = css`
${(props) =>
props.fullWidth &&
css`
width: 100%; // 1
justify-content: center; // 1
& + & { // 2
margin-left: 0; // 2
margin-top: 1rem; // 2
}
`}
`;
&가 제대로 동작하지 않는 부분에 대해 더 알고 싶으신 분들은 해당 이슈를 읽어보시면 도움이 될 것 같네요.
이유는 잘모르겠지만 버튼 안에 'button' 글자가 가운데 정렬이 안됩니다...
const StyleButton = styled.buttndisplay: inline-flex; ...
display: inline-flex; 밑에 align-items: center;를 넣으니까 가운데 정렬되긴해요 맞는건지 잘모르겠지만
하 백엔드개발잔데 css진짜 못해먹겠다 ㅋㅋㅋㅋㅋㅋㅋ
@heemaeng display:inline-flex말고 display:inline-block해보세요!
22/6/9 현재 본문에서는 useState 로 animate 상태값만 변경시켜주는데, css에서 animate 의 상태값을 참조할 수 있도록 코드를 추가해야 animate 상태 변화가 의미있어지는것 아닌지요?
styled-component로 만든 컴포넌트는 이벤트처리시 target의 value, id등을 받아오질 못합니다.
버튼 & + & 오류에 대해서 @YunhwanJung 님이 남기신 내용보다 아래와 같이 해보세요.
const fullWidthStyle = css`
${(props) => {
if (props.fullWidth && props.fullWidth === true)
return css`
width: 100%;
justify-content: center;
&.fullWidth + &.fullWidth {
margin-left: 0;
margin-top: 1rem;
}
`;
else
return css`
& + & {
margin-left: 1rem;
`;
}}
`;
const StyledButton = styled.button`
/* 공통 스타일 */
display: inline-flex;
outline: none;
border: none;
border-radius: 4px;
color: white;
font-weight: bold;
cursor: pointer;
padding-left: 1rem;
padding-right: 1rem;
/* 크기 */
${sizeStyles}
/* 색상 */
${colorStyles}
${fullWidthStyle}
`;
function Button({ children, color, size, outline, fullWidth, ...rest }) {
return (
<StyledButton
color={color}
size={size}
outline={outline}
fullWidth={fullWidth}
className={fullWidth ? 'fullWidth' : ''}
{...rest}
>
{children}
</StyledButton>
);
}
Button.defaultProps = {
color: 'blue',
size: 'medium',
};
export default Button;
@miriamme 님 덕분에 저도 명쾌해 졌습니다. 감사합니다. className을 설정하는 부분이 포인트인 것 같아서, className을 좀 더 직관적으로 세팅하는 코드로 아래와 같이 조금만 바꿔서 공유해봅니다.
Buttons.js
...
...
const fullWidthStyle = css`
${(props) => {
if (props.fullWidth)
return css`
width: 100%;
justify-content: center;
&.fullgaro + &.fullgaro {
margin-left: 0;
margin-top: 1rem;
}
`
else
return css`
& + & {
margin-left: 1rem;
`
}}
`
const StyledButton = styled.button`
/* 공통 스타일 */
outline: none;
border: none;
border-radius: 4px;
color: white;
font-weight: bold;
cursor: pointer;
padding-left: 1rem;
padding-right: 1rem;
/* 크기 */
${sizeStyles}
/* 색상 */
${colorStyles}
${fullWidthStyle}
`
function Button({ children, color, size, outline, fullWidth, ...rest }) {
return (
<StyledButton
color={color}
size={size}
outline={outline}
fullWidth={fullWidth}
className={fullWidth ? 'fullgaro' : ''}
{...rest}
>
{children}
</StyledButton>
)
}
Button.defaultProps = {
color: 'blue',
size: 'medium',
}
export default Button