const StyledDiv = styled.div`
width: 100px;
height: 50px;
p {
text-size: 15px;
color: black;
}
`
return (<StyledDiv><p>제목</p></StyledDiv>)
styled-components로 구성된 태그에 하위 컴포넌트에게 적용하고 싶은 스타일을 지정하면
해당 스코프를 탐색하여 하위 컴포넌트에게 스타일을 지정합니다.
=> 즉 하위 태그는 따로 만들어야 한다
=> 컴포넌트처럼 태그의 내용 자체를 props로 만들어서 상위 컴포넌트에서 넘겨줄 수 없다
참고링크 : https://flamingotiger.github.io/frontend/react/react-add-font/
컴포넌트 또는 함수 안에서 사용되어야 한다!!
React Hook "useState" cannot be called at the top level. React Hooks must be called in a React function component or a custom React Hook function react-hooks/rules-of-hooks
과제: 메뉴바 버튼을 누르면 모달이 뜨는 것
접근: 메뉴바 버튼 onClick 시 상태 변경으로 모달의 display 속성값 조작
문제: 모달을 컴포넌트로 만들 경우 import 해서 사용 시 state는 전역 스코프에서 쓸 수 없기 때문에 위치가 애매해진다
해결 방법1.
:(1) 메뉴바 버튼을 가지고 있는 부모 컴포넌트에서 state를 갱신해서
(2)하위 컴포넌트인 모달 컴포넌트의 속성을 변경해야 하므로
=> state를 부모에서 정의하고 모달 컴포넌트에 props로 보낸다
=> 이때 state 갱신 함수를 담고 있는 onClickHandler 함수도 같이 props로 보낸다
위와 같은 프로세스를 상태 끌어올리기라고 한다
리액트는 원래 위에서 아래로 흐르는 단방향 데이터 흐름을 가지고 있는데
하위 컴포넌트에서 상위 컴포넌트에게 영향을 줄 때 이런 원칙에 어긋나게 된다
그러므로 하위에서 props로 state와 이벤트 핸들러를 받기만 하고 실행은 상위에서 할 수 있도록 정의를 상위에서 해준다
단점
import, export 시 state, eventhandler, props의 상속 관계가 꼬일 때가 많다. 예를 들어 부모 컴포넌트에서 사용하는 변수, 함수들을 매번 props로 설정해서 보내주거나 해야 한다. 특히 메뉴 리스트 모달을 만들 때 내용뿐만 아니라 기능도 달라지니까 조건부로 설정하기 까다로웠다
.attrs
This is a chainable method that attaches some props to a styled component.
The first and only argument is an object that will be merged into the rest of the component's props.
The attrs object accepts the following values:
VALUES DESCRIPTION
Prop Value
: These can be of any type, except functions. They'll stay static and will be merged into the existing component props.
Prop Factory
: A function that receives the props that are passed into the component and computes a value, that is then going to be merged into the existing component props.
style
prop expects a mapping from style properties to values, not a string.위의 문제는 바로, {}괄호가 하나가 들어있었기 때문이다. style={color}의 문제이다. JSX에서 {}를 써서 JS를 표현한다. 그래서 아래의 코드로 바꾸어야 한다.
가장 밖의 {}는 JSX문법, 안의 {}객체 리터럴이다.