FrontEnd :-)

[RN] study 4week / 할일 목록 만들기 ①-② 본문

React Native

[RN] study 4week / 할일 목록 만들기 ①-②

code10 2023. 2. 26. 14:09

React Navtive 스터디 4week

도서: [리액트 네이티브를 다루는 기술 / 김민준 / 길벗]

(3장 할일 목록 만들기 ①)

 

3.1 프로젝트 기반 다지기

3.2 TextInput으로 사용자 키보드 입력받기

3.3 정리


키보드 안 보이면, command + K

3.2.1 KeyboardAvoidingView로 키보드가 화면을 가리지 않게 하기

//App.tsx

import React from 'react';
import {KeyboardAvoidingView, Platform, StyleSheet} from 'react-native';
import {SafeAreaProvider, SafeAreaView} from 'react-native-safe-area-context';
import AddTodo from './components/AddTodo';
import DateHead from './components/DateHead';
import Empty from './components/Empty';

function App() {
  const today = new Date();

  return (
    <SafeAreaProvider>
      <SafeAreaView edges={['bottom']} style={styles.block}>
        <KeyboardAvoidingView
          behavior={Platform.OS === 'ios' ? 'padding' : undefined}
          style={styles.avoid}>
          <DateHead date={today} />
          <Empty />
          <AddTodo />
        </KeyboardAvoidingView>
      </SafeAreaView>
    </SafeAreaProvider>
  );
}

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

export default App;

3.2.1.1 Platform.OS와 삼항연산자 대신 Platform.select 사용하기

(1)
behavior={Platform.OS === 'ios' ? 'padding' : undefined}
(2)
behavior={Platform.select({ios: 'padding', android: undefined})}
(3)
behavior={Platform.select({ios: 'padding'})}

3.2.2 useState로 텍스트 상태 값 관리하기

3.2.3 커스텀 버튼 만들기

 

버튼 효과 주는 방법. 터치할 수 있는 영역을 다음 컴포넌트 중 하나로 감싸면 된다. 

TouchableHighlight: 터치했을 때 배경색을 변경

TouchableNativeFeedback: 터치했을 때 안드로이드에서 물결 효과, 안드로이드에서만 사용 가능. iOS에서 사용 시 오류 발생

TouchableOpacity: 터치했을 때 투명도 조정

TouchableWithoutFeedback: 터치했을 때 아무 효과도 적용하지 않음.

 

<TouchableOpacity activeOpacity={0.5}> ... </TouchableOpacity>

//투명도값 설정 안하면 기본 0.2

버튼 터치 효과

1. iOS => 투명도

2. 안드로이드 => 물결 효과 (overflow: hidden 으로 원 버튼 바깥까지 나타나는 걸 방지)

리팩토링까지한 코드

//App.tsx

(...)

function AddTodo() {
  const [text, setText] = useState('');

  const button = (
    <View style={styles.buttonStyle}>
      <Image source={require('../assets/icons/add_white/add_white.png')} />
    </View>
  );

  return (
    <View style={styles.block}>
      <TextInput
        placeholder="할일을 입력하세요"
        style={styles.input}
        value={text}
        onChangeText={setText}
      />
      {Platform.select({
        ios: <TouchableOpacity activeOpacity={0.5}>{button}</TouchableOpacity>,
        android: (
          <View style={styles.circleWrapper}>
            <TouchableNativeFeedback>{button}</TouchableNativeFeedback>
          </View>
        ),
      })}
    </View>
  );
}

const styles = StyleSheet.create({
  block: {
    backgroundColor: 'white',
    height: 64,
    paddingHorizontal: 16,
    borderColor: '#bdbdbd',
    borderTopWidth: 1,
    borderBottomWidth: 1,
    alignItems: 'center',
    flexDirection: 'row',
  },
  input: {
    flex: 1,
    fontSize: 16,
    paddingVertical: 8,
  },
  buttonStyle: {
    width: 48,
    height: 48,
    alignItems: 'center',
    justifyContent: 'center',
    backgroundColor: '#f48fb1',
    borderRadius: 24,
  },
  circleWrapper: {
    overflow: 'hidden',
    borderRadius: 24,
  },
});

export default AddTodo;

 

버튼 눌렀을 때 인풋창 텍스트 비우고, 키보드 닫기

  const onPress = () => {
    setText('');
    Keyboard.dismiss();
  };

3.2.4 TextInput에 onSubmitEditing 및 returnKeyType 설정하기

키보드 Enter 눌렀을 때도 onPress 함수 호출하도록, Enter 타입 지정도

 <TextInput
        onSubmitEditing={onPress}
        returnKeyType="done"
/>

returnKeyTpye Props에 값 지정

플랫폼 공통 - done (완료) - go (이동) - next (다음) - search (검색) - send (보내기)

iOS 전용 - defaul (기본) - emergency-call (긴급 통화) - google (검색) - join (가입) - route (이동) - yahoo (검색)

안드로이드 전용 - none (일반 Enter) - previous (뒤로)

 

※ Platform.OS 에 따라 조건부 설정 잘해야 함!!

Comments