storybook설치하기
#clone the template
npx degit chromaui/intro-storybook-react-template taskbox
//여기서 taskbox는 dir이름임
cd taskbox
//파일 오픈해서,src
하위에stories
dir생성되었는지 확인.
//package.json확인해서 storybook실행 명령어 있는지 확인.
#install dependecies
yarn
//마지막으로yarn storybook
실행하면 localhost가 열림.
styled component는 컴포넌트 기반으로 css를 작성할 수 있게 해줌.
장점:
1.네이밍이나 최적화를 신경안써도 됨.
2.css를 컴포넌트 안으로 캡슐화함.
단점: 페이지 로드면에서 느림.
설치
#with npm
$npm install --save styled-components
#with yarn
$ yarn add styled-components
#권장사항 : 아래 코드를 package.json에 추가.{ "resolutions": { "styled-components": "^5" } }
위의 코드를 추가함으로써 여러버전의 styled컴포넌트가 설치되어 발생하는 문제를 줄여줌.
생성
1.js에서 변수를 선언하듯 변수를 만들어준다
2. styled를 써준다
2.tag속성을 정의해준다
3. 백틱(``)안에 기존 css를 이용하여 스타일 속성을 정의해준다const Button = styled.a` margin:0; padding:0; width: 11rem; `;
1.
Button
2.styled.
3.a
여기서는 a태그
4. 그리고 `` 백틱안에 css문법대로 속성 정의
5.만들어진 변수는 기존 컴포넌트 사용방식으로 사용할 수 있다.
상속
// 기존의 Button 컴포넌트에 Tomato 컴포넌트만을 위한 새로운 속성 추가 const Tomato = styled(Button)` color: tomato; border-color: tomato; `;
styled(Button)
이런식으로 Button의 속성을 상속해오고,
새로운 속성을 추가해줄 수 있다.
함수전달하고, 그 함수 안에서 props사용가능
//Button 컴포넌트 ... background: ${ (props) => (props.primary ? "red" : "yellow") }; color: ${ (props) => (props.primary ? "yellow" : "red") } //App 컴포넌트 ```js ... <Button>Normal</Button> <Button primary>Primary적용된 컴포넌트</Button> //함수를 전달받음. ...
props받아오기
>
```js
const Input = styled.input`
color: ${(props)=> props.inputColor || "red"}
`;
export default function App(){
return (
<div>
<Input defaultValue="김김김" type="text"/> //red
<Input defaultValue="유유유" type="text" inputColor="blue"/> //blue
</div>
)
}
React는 예외적인 상황에서 useRef로 DOM노드, 엘리먼트 그리고 리액트컴포넌트의 주소값을 참조할 수 있다.
.current
프로퍼티에 변경가능한 값을 담고 있는 'box'이다.(객체)ref
객체에 일반변수뿐 아니라, DOM
을 담을 수 있다. const InputRef = () => {
const inputRef = useRef(null);
const onFocus = () => {
inputRef.current.focus();
};
return (
<>
<input type="text" ref={inputRef} />
<button onClick={onFocus}>inputFocus</button>
</>
);
}
<input ref={inputRef} />
처럼 ref에 inputRef
라는 객체를 할당해주면,inputRef.current
에 input태그에 해당하는 DOM이 담김.
사용법
const 주소그릇 = useRef(참조자료형)
re-render되어도 주소값 변동은 없다<div> <input ref={주소그릇} type="text" /> </div>