#state 값 변경
// 두 가지 방식으로 state 값 변경해줄 수 있음.
setCounter(cur => cur + 1) // setCounter의 첫 번째 argument는 state 값이다.
setCounter(cur + 1) // 선언하지 않을 경우 자동으로 연산
#label-input 값 연결
label과 checkbox input 연결하여, label을 클릭하여도 체크가 실행되게 만들고 싶을 때,
htmlFor 옵션을 통해 연결가능.
label 대신에 image 등 다른 tag 요소도 사용가능
<label htmlFor='check'>체크하기</lable>
<input id='minutes' type='checkbox' />
#변화하는 input 값 event.target.value로 가져오기
const [minutes, setMinutes] = React.useState();
const onChange = (event) => {
setMinutes(event.target.value); //동적으로 변하는 state 값을 event.target.value로 잡아서 관리
}
<input
value={minutes} //input의 value를 state로 관리
id='minutes'
type='number'
onChange={onChange}
/>
#input value 값 조건에 따라 다르게 표시하기
// value에 삼항연산자 사용하여 state를 조건식으로 업데이트할 수 있음
<input
value={flipped ? amount : Math.round(amount / 60)}
/>
#props 사용
props를 통해
- 상위 컴포넌트에서 하위 컴포넌트로 값 전달
- 렌더링될 때 component의 값을 선언하여 전달할 수 있음
function Btn ({ text, big }) {
return (
<button
style={{
fontSize: big ? 18 : 16
}}
>
{text}
</button>
)
}
function App() {
return (
<div>
<Btn text='save change' big={true} /> // text와 big이 props이고, save change와 true가 props 값이다.
<Btn text='continue' big={false} />
</div>
)
}
// props를 통해 같은 틀이지만 내용물 & 모양이 다른 <Btn> 컴포넌트를 쉽고 빠르게 생성할 수 있게됨.
#react memo
props가 변화된 컴포넌트만 렌더링하기위한 설정
const MemorizedBtn = React.memo(Btn) // Btn 컴포넌트의 원래값을 기억하여 렌더링할 때 props가 바뀐 컴포넌트만 렌더링
function App() {
const [value, setValue] = React.useState('save change');
const changeValue = () => setValue('revert change')
return (
<div>
<MemorizedBtn text={value} onClick={changeValue}/>
<MemorizedBtn text='continue' /> // props가 바뀌지 않았기 때문에 렌더링되지 않음
<div>
)
}
#prop의 type 확인
prop-type 패키지를 설치하여 전달되는 props의 type이 의도한 대로 전달되는지 검수할 수 있음.
Btn.propTypes = {
text: PropTypes.string,
fontSize: PropTypes.number
}
#css-module
컴포넌트에 개별적으로 css style 적용할 때 사용
컴포넌트에 공통적으로 style 적용하는 장점 가져가면서 필요할 때 개별적으로 접근하여 수정할 수 있음.
하지만 별도로 많은 css 파일을 만들고 import 해줘야하는 단점 존재
import styles from ./Button.module.css
return <button className={styles.btn}> // html 상에서 style class 랜덤하게 생성
'TIL' 카테고리의 다른 글
TIL) 분산 원장(DLT)의 개념 및 다양한 구현 방법 (0) | 2022.06.13 |
---|---|
TIL) 웹 호스팅 관련 사이트 : netlify, replit (0) | 2022.06.12 |
TIL) 독립적 앱 실행환경 제공하는 Docker (0) | 2022.06.10 |
TIL) 인증 중개 메커니즘: OAuth(feat. github을 사용한 Sprint review) (0) | 2022.06.10 |
TIL) http 통신 라이브러리: Axios (0) | 2022.06.08 |