study: 리네다기 | 6장 - Children Props, Render Props

Lumpen·2023년 4월 13일
0

Study

목록 보기
57/92

children Props

children Props 는 Text 컴포넌트에서 사용하는 것 처럼 컴포넌트 태그 사이에 넣어준 값

Render Props는 이 children의 타입을 함수 형태로 받아오는 패턴으로
일반적으로는 컴포넌트에 필요한 값을 Props로 넣어주지만
Render Props를 사용하면 반대로 우리가 사용할 컴포넌트에서 특정 값을 밖으로 빼내와 사용할 수가 있있다

import React from 'react';
import {StyleSheet, View, Text} from 'react-native';
import LogContext from '../contexts/LogContext';

function FeedsScreen() {
  return (
    <View style={styles.block}>
      <Box>
        <Text>1</Text>
      </Box>
      <Box>
        <Text>2</Text>
      </Box>
      <Box>
        <Text>3</Text>
      </Box>
    </View>
  );
}

function Box({children}) {
  return <View style={styles.box}>{children}</View>;
}
  const styles = StyleSheet.create({
    box: {
    borderWidth: 2,
    padding: 16,
    borderBottomColor: 'black',
    marginBottom: 16,
  },
});

export default FeedsScreen;

Box 컴포넌트 태그 사이에 넣은 JSX를 children이라는 Props로 받아와서 사용할 수 있다

Render Props

Render Props 는 children 타입을 함수 형태로 받아오는 패턴이다
일반적으로 우리가 컴포넌트에 필요한 값을 Props 에 넣어주는 형태이지만
Render Props 를 사용하면 사용할 컴포넌트에서 특정 값을 꺼내어 사용할 수 있다

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

function FeedsScreen() {
  return (
    <View style={styles.block}>
      <Box>{(value) => <Text>{value}</Text>}</Box>
    </View>
  );
}

function Box({children}) {
  return <View style={styles.box}>{children('Hello World')}</View>;
}

const styles = StyleSheet.create({
  box: {
    borderWidth: 2,
    padding: 16,
    borderBottomColor: 'black',
    marginBottom: 16,
  },
});

export default FeedsScreen;

이렇게 하면 Text 에서 'Hello World' 를 받아와 사용할 수 있다
상태 끌어올리기랑 비슷한 느낌

Render Props는 리액트에 Hooks가 없던 시절 사용해쓴ㄴ데 요즘은 사용할 일이 그렇게 많지 않다

profile
떠돌이 생활을 하는. 실업자는 아니지만, 부랑 생활을 하는

0개의 댓글