Warning: Function components cannot be given refs. Attempts to access this ref will fail. Did you mean to use React.forwardRef()?

cooking_123·2024년 3월 30일

React Native TIL

목록 보기
23/30
            <CheckInput
                ref={refPassword}
                label='Password'
                placeholder='Password'
                returnKeyType='done'
                value={password}
                onChangeText={setPassword}
            />

컴포넌트 자체에다가 ref를 설정해주니 아래와 같은 오류가 발생했다.

Warning: Function components cannot be given refs. Attempts to access this ref will fail. Did you mean to use React.forwardRef()?

경고 메시지에서 안내하고 있듯이 리액트에 forwardRef를 사용해주면 된다.

1. 해당 컴포넌트에 forwardRefimport해준다.

2. 그리고 forwardRef를 이용해서 CheckInput.js 컴포넌트 전체를 감싸주면 된다.

3. 두번째 파라미터로 ref를 넣어줘야한다.

CheckInput.js

import React, { useState, forwardRef } from 'react';
(...)
const CheckInput = forwardRef(//forwardRef로 감싸주기
    ({ props }, ref) => {//두번째 파라미터로 ref를 넣어주기
        return (
            <Container>
				  <StyledInput
                    ref={ref}
                />
            </Container>
        );
    }
);

0개의 댓글