[TIL]React/Typescript Styled-component & Interface

ohoho·2024년 10월 21일

슬기로운스터디

목록 보기
33/54

오늘 공부한것 & 기억할 내용

Styled-component

  1. 다른 스타일 컴포넌트를 사용하고 싶을때는 styled()를 사용해준다.
const Box = styled.div`
	background-color: ${(props) => props.bgColor}
	width:100px;
	height:100px;
`
const Circle = styled(Box)`
	border-radius:50px;
`
return(
	<Box bgColor="tomato"/>
)
  1. 스타일은 쓰고 싶은데 속성 변경을 해주고 싶을때 as를 사용한다.
const Box = styled.div`
	background-color: ${(props) => props.bgColor}
	width:100px;
	height:100px;
`
return(
  	//Box의 스타일은 그대로 사용하면서 a링크로 변경됨
	<Box bgColor="tomato" as="a"/>
)
  1. HTML태그 속성을 style에 적을 수 있다.
const Input = styled.input.attrs({required:true,minLength:10})`
	background-color:#fff;
`
  1. animation을 만들고 싶을때
//keyframes import
import styled,{keyframes} from "styled-components";

const rotateAni = keyframes`
	from{}
	to{}
`	
const Box = styled.div`
	animation:${rotateAni}
`
  1. 하위요소에게 style을 주고 싶을때
//scss처럼 사용한다
const Box = styled.div`
	span{
		&:hover{

		}
	}
`

//상위 styled 컴포넌트 사용
const Emoji = styled.span``
const Box = styled.div`
	${Emoji}$:hover{
	}
`
  1. theme을 사용할때
//index.js
import {ThemeProvider} from "styled-components"
const darkTheme = {
	textColor:"white",
  	backgroundColor:"block"
}
const whiteTheme = {
	textColor:"block",
  	backgroundColor:"white"
}

//ThemeProvider의 하위 컴포넌트들은 theme안의 object에 접근이 가능하다.
<ThemeProvider theme={darkTheme}>
      <App />
</ThemeProvider>


//App.js
const Title = styled.h1`
	color:${props => props.theme.textColor}
`

InterFace

  • styled-component와 props에 interface적용하기
import styled from "styled-components";

//styled interface
interface ContainerProps{
    $bgColor:string
    $borderColor:string
}

const Container = styled.div<ContainerProps>`
    width:100px;
    height:100px;
    background-color:${props => props.$bgColor};
    border:3px solid ${props=> props.$borderColor};
`

//props interface
interface CircleProps {
    $bgColor:string
    $borderColor?:string
    text?:string
}

function Circle({$bgColor,$borderColor,text = 'default text'}:CircleProps){
    return(
        <>
        {/* props의 interface에만 option으로 넣어주고 ??을 사용하여 디폴트값을 뒤에 넣어준다
        (??앞에 값이 null이거나 undefined이면 오른쪽 값을, 그렇지 않으면 왼쪽 값을 반환하는 논리연산자)
         */}
        <Container $bgColor={$bgColor} $borderColor={$borderColor ?? $bgColor}>
            {text}
        </Container>
        </>
    )
}
export default Circle 

이슈

  • bgColor와 borderColor작성하면서 console창에 에러 발생

작동은 되지만 에러가 뜨길래 찾아봤더니 camelCase로 속성을 정의 하면 DOM에도 속성을 끼칠 수 있기에 styled-component에서만 사용하는 속성은 $ 을 사용해 DOM으로 prop을 전달하지 않게 한다.

styled-component $접두사 사용 이유
styled-component $prefix 장점

useState / e

function App() {
  const [value,setValue] = useState<string>("");
  //HTMLInputElement을 사용하면 console.dir(e)했을때와 비슷한 기능을 얻을 수 있다.
  //e만 찍어도 뒤에올 속성들이 자동으로 보여짐
  const onChange = (e:React.FormEvent<HTMLInputElement>) => {
    //const {currentTarget:{value}} = e;
     const {value} = e.currentTarget;
     setValue(value)
  }
  const onSubmit = (e:React.FormEvent<HTMLFormElement>) => {
    
  }
  return (
    <>
     <form>
      <input type="text" placeholder='name'/>
      <button>Click</button>
     </form>
    </>
  );
}

ReactJs에서만 사용하는 SyntheticEvent

배운점 & 느낀점

타입스크립트를 리액트에서 사용하는법을 배웠는데, 배우기전에는 타입을 지정해주는건 좋은데 번거롭다라는 생각을 했었는데 리액트에서 타입스크립트를 사용하니까 속성들이 자동으로 보여주는 기능도 있고 오히려 코드짤때 더 편리하다는 생각을 했다.

0개의 댓글