TS 작성 중 다음과 같은 오류 발생
'forwardedref<unknown>' 형식은 'legacyref<htmlinputelement> | undefined' 형식에 할당할 수 없습니다.
'mutablerefobject<unknown>' 형식은 'legacyref<htmlinputelement> | undefined' 형식에
할당할 수 없습니다. 'mutablerefobject<unknown>' 형식은 'refobject<htmlinputelement>'
형식에 할당할 수 없습니다. 'current' 속성의 형식이 호환되지 않습니다.
'unknown' 형식은 'htmlinputelement | null' 형식에 할당할 수 없습니다.
forwardRef 로 작성한 함수에서 ref type을 다음과 같이 지정해주었다.
ref?: React.ForwardedRef<HTMLInputElement> | undefined
이것도 해봤더니 되긴함)
ref?: React.LegacyRef<HTMLInputElement> | undefined
적용한 전체코드
import React, { forwardRef } from 'react';
interface InputProps {
title: string;
..
onChange: () => void;
}
export default forwardRef(function Input(
{
title,
onChange,
...
}: InputProps,
ref?: React.ForwardedRef<HTMLInputElement> | undefined
) {
return (
<label>
<p className={InputTitle}>{title}</p>
<input
type={type}
..
ref={ref}
/>
</label>
);
});
[Typescript] useRef를 다른 컴포넌트에 props로 전달할 때
문제 상황 > Arrow Function Regular Function
velog.io
https://zerodice0.tistory.com/244
[React] MutableRefObject와 LegacyRef
Input의 onChange에 setState를 할당해서 값이 바뀔때마다 상태값이 변경되도록 설정했더니, 매번 Input에 입력한 값이 변경될 때마다 렌더링이 다시 되는 기염을 토했다. 당연한 얘긴 줄 알고 있었는데
zerodice0.tistory.com
[React] react-hook-form register 등록 방법 커스텀하기
안녕하세요. J4J입니다. 이번 포스팅은 react-hook-form register 등록 커스텀하는 방법에 대해 적어보는 시간을 가져보려고 합니다. register를 props로 넘기기 첫 번째 방법은 register를 props로 넘기는 방법
jforj.tistory.com
* 값이 없을 경우 해당 input 에 focus가 가도록 설정했다.
const titleUpdateInput = useRef();
...
if (!UpdateData.title) {
alert('제목을 입력해주세요.');
titleUpdateInput.current.focus();
}
여기서 TS를 적용하여 아래와 같이 ? 옵셔널체이닝을 이용하여 undefined일때의 오류도 해결했지만
never형식에 focus속성이 없다고 오류가 발생했다.
titleUpdateInput.current?.focus();
위 코드는 참고로 아래와 동일하다.
if (titleUpdateInput.current) {
titleUpdateInput.current?.focus();
}
해결: useRef 에 type을 지정해주지 않아서 찾지 못해 생긴 에러였다. 아래 코드로 해결하였다.
const titleUpdateInput = useRef<HTMLInputElement>(null);
'Type Script > Type 적용' 카테고리의 다른 글
[TS] 객체로 이루어진 배열 type(feat.props) (1) | 2023.03.08 |
---|---|
[TS]TypeScript에서 useRef type 사용 방법 (0) | 2023.03.08 |
[TS] 객체 type (아직 정해지지 않은 key,value) (0) | 2023.03.08 |
[TS] change, submit e매개변수 type, onChange type (feat.Type보는 방법) (0) | 2023.03.07 |
[TS] children Type (0) | 2023.03.07 |