TypeScript(2)-React에서 사용

개미는뚠뚠·2022년 11월 23일
0

TypeScript

목록 보기
2/2
post-thumbnail

react에서 typescript를 사용하려는데 도저히 어떻게 사용해야할지 모르겠어서 정리를 해보려고 한다.
해당 내용은 실전에서 바로 사용하려고 하기 때문에 설명글은 아니다...나를 위한 글...😂


  • JSX는 DOM 요소를 표현하기 위해 사용하는 React의 태그문법이다.
  • 리액트 jsx문법을 사용하려면 tsx확장자로 코드를 작성해야 한다.

1. JSX Element

// 1
const element: JSX.Element = (
  <h1>
    Hello, World!
  </h1>
); 
//일반적인 사용

//2
const str: string = 'Hello, World!';
const element: JSX.Element = (
  <h1>
    {str}
  </h1>
); 
> //중괄호를 사용하면 표현식을 사용

//3 
const element: JSX.Element = React.createElement(
  'h1',
  {className: 'greeting'},
  'Hello, world!'
); 
//JSX 문법은 위처럼 JSX 객체로 변환된 뒤에 element에 저장되고, jsx문법은 필수가 아니다.

2. event 조작하기

리액트에서 onClcik 혹은 onChange 메서드에 event를 인자로 받아 조작을 하려고 했으나 자꾸 화나게 에러가 발생했다...

type LoginType = {userId: string | undefined, userPw: string | undefined}
    const [userInput, setUserInput] = useState({userId : "", userPw: ""})
    const inputLoginData = (e :any) => {
        setUserInput({...userInput, [e.target.name]: e.target.value})
    }
    const loginSumbit = () => {
        let testLoginInfo :LoginType = {userId : "eogh773", userPw : "eogh12"}
        console.log("유저인풋: ",userInput)
        console.log("로그인 데이터: ", testLoginInfo)
        if(userInput.userId === testLoginInfo.userId && userInput.userPw === testLoginInfo.userPw){
            console.log("로그인 성공")
        }else{
            console.log("로그인 실패")
        }
    }

그래서 내가 급하게 조치한 방법은 인자 값의 타입을 any로 주는 것이였다...그러다 이러면 타입쉴드를 해제한다는 의미로 타입스크립트를 쓰는 의미가 없지 않나!!!!!!! 싶어서 다른 방법을 찾아보려고 엄청 노력했다.

그 결과...뭔가 찾은 거 같다!!!

type LoginType = {userId: string | undefined, userPw: string | undefined}
    const [userInput, setUserInput] = useState({userId : "", userPw: ""})
    const inputLoginData = (e :React.FormEvent<HTMLInputElement>) => {
        setUserInput({...userInput, [e.currentTarget.name]: e.currentTarget.value})
    }
    const loginSumbit = () => {
        let testLoginInfo :LoginType = {userId : "eogh773", userPw : "eogh12"}
        console.log("유저인풋: ",userInput)
        console.log("로그인 데이터: ", testLoginInfo)
        if(userInput.userId === testLoginInfo.userId && userInput.userPw === testLoginInfo.userPw){
            console.log("로그인 성공")
        }else{
            console.log("로그인 실패")
        }
    }

블로그를 이쁘게 꾸미지 못해서 잘 보이지 않겠지만
"해결책1. 이벤트 인자를 React.FormEvent 로 할당해주었다!!!!"
그러나 이벤트 인자의 타입 문제는 해결이 되었다.
그러나 두번째 문제로 target이 에러가 나는 것이였다...
그러나 또 금방 잡았다!!!
해결책2. 바로 위에 코드와 같이 target부분을 e.currentTarget.~~ 로 지정해주는 것이였다.
이후 나의 이벤트 이슈는 해결이 되었다! 와~~~짝짝짝👍

3. 타입스크립트에서 쓸 수 있는 HTML 타입

HTML 타입에는 Element, HTMLElement, HTMLAnchorElement 등이 있는데
Element에 들어있는걸 복사해서 몇개 더 추가해서 HTMLElement 타입을 만들어놨고

ex) a 태그는 HTMLAnchorElement
img 태그는 HTMLImageElement
h4 태그는 HTMLHeadingElement

HTMLElement에 들어있는걸 복사해서 몇개 더 추가해서 HTMLAnchorElement 타입을 만들었다.

ex) href, style, class, id 이런 속성을 가질 수 있는 타입

0개의 댓글