15.12.3 댓글 삭제 기능 구현하기

    이번에는 댓글을 삭제하는 기능을 만들어봅시다. 댓글 삭제 기능을 만들려면 기존에 만든 CommentItem을 조금 수정해야 합니다.

    이 기능을 구현하기 위해 CommentItem에 세 가지 Props를 추가해야 합니다. 우선 보이는 댓글이 자신의 댓글인지 분별하는 isMyComment Props를 추가하세요. 이 값이 true면 댓글 컴포넌트에 수정과 삭제 버튼이 나타납니다. 그리고 각 버튼을 눌렀을 때 호출할 onRemoveonModify Props를 추가하세요.

    components/CommentItem.tsx

    import React from 'react';
    import {View, StyleSheet, Text, Pressable} from 'react-native';
    
    export interface CommentItemProps {
      id: number;
      message: string;
      username: string;
      publishedAt: string;
      isMyComment: boolean;
      onRemove(id: number): void;
      onModify(id: number): void;
    }
    
    function CommentItem({
      id,
      message,
      username,
      publishedAt,
      isMyComment,
      onRemove,
      onModify,
    }: CommentItemProps) {
      const formattedDate = new Date(publishedAt).toDateString();
    
      const handleRemove = () => onRemove(id);
      const handleModify = () => onModify(id);
    
      return (
        <View style={styles.block}>
          <View style={styles.head}>
            <Text style={styles.username}>{username}</Text>
            <Text style={styles.date}>{formattedDate}</Text>
          </View>
          <Text style={styles.message}>{message}</Text>
          {isMyComment && (
            <View style={styles.actionButtons}>
              <Pressable
                style={({pressed}) => pressed && styles.pressed}
                hitSlop={8}
                onPress={handleModify}>
                <Text style={styles.buttonText}>수정</Text>
              </Pressable>
              <View style={styles.separator} />
              <Pressable
                style={({pressed}) => pressed && styles.pressed}
                hitSlop={8}
                onPress={handleRemove}>
                <Text style={styles.buttonText}>삭제</Text>
              </Pressable>
            </View>
          )}
        </View>
      );
    }
    
    const styles = StyleSheet.create({
      block: {
          paddingTop: 8,
          paddingBottom: 16,
      },
      head: {
          flexDirection: 'row',
          justifyContent: 'space-between',
      },
      username: {
        fontWeight: 'bold',
      },
      date: {
        color: '#546e7a',
        fontSize: 10,
        marginTop: 4,
      },
      message: {
        marginTop: 4,
      },
        actionButtons: {
        marginTop: 24,
        justifyContent: 'flex-end',
        flexDirection: 'row',
      },
        separator: {
        width: 8,
      },
        buttonText: {
        fontSize: 12,
        color: '#546e7a',
      },
        pressed: {
        opacity: 0.75,
      },
    });
    
    export default CommentItem;
    신간 소식 구독하기
    뉴스레터에 가입하시고 이메일로 신간 소식을 받아 보세요.