React-Native ref & custom

이홍경·2022년 1월 24일
0
post-thumbnail

컴포넌트 내부의 컴포넌트에 ref 설정하기

  • forwardRef 사용해야 한다.
### 자식 컴포넌트 
import React from 'react';
import { StyleSheet, TextInput } from 'react-native';

const CustomInput =({ hasMargin, ...rest }, ref) => {
  return (
    <TextInput 
      style={[styles.input, hasMargin && styles.margin]}
      ref={ref}
      {...rest}
    />
  )
}
생략
export default React.forwardRef(CustomInput);

/// 같은 방식이다.
  const CustomInput = React.forwardRef(({ hasMargin, ...rest}, ref) => {})
///

import React,{ useRef } from 'react'
import ...'react-native';
import CustomInput from '...'

const Screen = () => {
  const passwordRef = useRef();

  ...
  return(
    ...
    <CustomInput 
      ref={passwordRef}
      onSubmitEditing={() => {
        ...working...
        passwordRef.current.focus();
      }}
    />
    ...
  )
}

커스텀 버튼 만들기

import React from 'react';
import { Pressable, View, Text, Platform, StyleSheet } from 'react-native;

const CustomButton = ({ title, onPress, hasMargin, theme }) => {
  const isPrime = theme === 'prime';

  return (
    <View style={[styles.overflow, hasMargin && styles.margin]}> // 클릭시 애니메이션 넘침 방지 overflow hidden
      <Pressable 
        onPress={onPress}
        style={({ pressed }) => [
          styles.wrapper, 
          isPrime && styles.primeWrapper,
          Platform.OS ==='ios' && pressed && {opacity: .5}
        ]}
        android_ripple={{ color: '#fff' }}

        <Text
          style={[
             styles.text,
             isPrime ? styles.primeStyle : styles.secondStyle,
          ]}

          {title}
        </Text>
      </Pressable>
    </View>
  )
}

CusotomButton.defaultProps = {
  theme: 'prime'
}

const styles = StyleSheet.create({
  margin: {
    marginBottom: 8
  },
  primeWrapper: {
    backgroundColor: '#6200ee',
  },
  primeStyle: {
    color: '#fff'
  },
  secondStyle: {
    color: '#6200ee'
  }
})

export default CustomButton;
profile
개발자를 꿈꾸는 자

0개의 댓글