본문 바로가기
카테고리 없음

[React Native] 3-5 useRef로 컴포넌트 래퍼런스 선택하기

by InfoJun 2023. 3. 15.
반응형

useRef는 함수 컴포넌트 에서 컴포넌트의 래퍼런스를 선택 할 수 있게 하는 Hook입니다.

 

제목을 입력후 Enter을 누르면 포커스를 이동시키고 싶다면 

 

이럴 때는 내용의 TextInput의 래퍼런스를 포커스 해줘야합니다

 

componets/WriteEditor.js

import React, {useRef} from 'react';
import {View, StyleSheet, TextInput} from 'react-native';

function WriteEditor({title, body, onChangeTitle, onChangeBody}) {
  const bodyRef = useRef();
  return (
    <View style={styles.block}>
      <TextInput
        placeholder={'제목을 입력하세요'}
        style={styles.titleInput}
        returnKeyType={'next'}
        onChangeText={onChangeTitle}
        value={title}
      />
      <TextInput
        placeholder={'당신의 오늘을 기록해보세요'}
        style={styles.bodyInput}
        multiline
        textAlignVertical="top"
        onChangeText={onChangeBody}
        value={body}
        ref={bodyRef}
      />
    </View>
  );
}

const styles = StyleSheet.create({
  block: {
    flex: 1,
    padding: 16,
  },
  titleInput: {
    paddingVertical: 0,
    fontSize: 18,
    marginBottom: 16,
    color: '#263238',
    fontWeight: 'bold',
  },
  bodyInput: {
    flex: 1,
    fontSize: 16,
    paddingVertical: 0,
    color: '#263238',
  },
});

export default WriteEditor;

다음과 같이 ref를 생성하여 TextInput의 Props로 지정해 주면 선택할 수 있습니다

  • .focus() : TextInput에 포커스를 잡아줍니다.
  • .blur() : TextInput에 포커스를 해제합니다.
  • .clear() : TextInput의 내용을 모두 비웁니다.

 

이제 제목 TextInput에서 onSubmitediting Props를 통해 Enter로 내용 TextInput으로 보내겠습니다.

import React, {useRef} from 'react';
import {View, StyleSheet, TextInput} from 'react-native';

function WriteEditor({title, body, onChangeTitle, onChangeBody}) {
  const bodyRef = useRef();
  return (
    <View style={styles.block}>
      <TextInput
        placeholder={'제목을 입력하세요'}
        style={styles.titleInput}
        returnKeyType={'next'}
        onChangeText={onChangeTitle}
        value={title}
        onSubmitEditing={() => {
          bodyRef.current.focus();
        }}
      />
      
      (...)

 

다음과 같이 쓰고 제목에서 Enter을 눌러보세요.

 

제목에서 내용으로 포커스가 이동할 것입니다.

 


KeyboardAvoidingView로 화면 감싸기

내용 TextInput에서 Enter을 여러번 눌러서 기본적으로 보이는 줄 수를 초과할 경우

 

안드로이드에서는 별 문제 없지만 ios에선 하단 내용이 잘리게 됩니다.

 

따라서 KeyboardAvoidingView로 WriteScreen 내부의 내용을 감싸줘야합니다.

 

components/WriteScreen.js

import React from 'react';
import {View, StyleSheet, KeyboardAvoidingView, Platform} from 'react-native';
import {SafeAreaView} from 'react-native-safe-area-context';
import WriteHeader from '../components/WriteHeader';
import WriteEditor from '../components/WriteEditor';

function WriteScreen() {
  return (
    <SafeAreaView style={styles.block}>
      <KeyboardAvoidingView
        style={styles.avoidingView}
        behavior={Platform.OS === 'ios' ? 'padding' : undefined}>
        <WriteHeader />
        <WriteEditor />
      </KeyboardAvoidingView>
    </SafeAreaView>
  );
}

const styles = StyleSheet.create({
  block: {
    flex: 1,
    backgroundColor: 'white',
  },
  avoidingView: {
    flex: 1,
  },
});

export default WriteScreen;

WriteScreen에서 텍스트 상태 관리하기

screens/WriteScreen.js

 

import React, {useState} from 'react';
import {View, StyleSheet, KeyboardAvoidingView, Platform} from 'react-native';
import {SafeAreaView} from 'react-native-safe-area-context';
import WriteHeader from '../components/WriteHeader';
import WriteEditor from '../components/WriteEditor';

function WriteScreen() {
  const [title, setTitle] = useState('');
  const [body, setBody] = useState('');

  return (
    <SafeAreaView style={styles.block}>
      <KeyboardAvoidingView
        style={styles.avoidingView}
        behavior={Platform.OS === 'ios' ? 'padding' : undefined}>
        <WriteHeader />
        <WriteEditor
          title={title}
          body={body}
          onChangeTitle={setTitle}
          onChangeBody={setBody}
        />
      </KeyboardAvoidingView>
    </SafeAreaView>
  );
}

(...)

 

다음과 같이 useState를 사용하여 WriteEditor에 Props로 전달해 주면 됩니다.

반응형

댓글