• 로그인
  • 장바구니에 상품이 없습니다.

home2 게시판 React 게시판 댓글 삭제버튼이 두번클릭해야 index값을 받아와요. T^T

댓글 삭제버튼이 두번클릭해야 index값을 받아와요. T^T

  • 이 주제에는 6개 답변, 3명 참여가 있으며 유순복3 년 전에 전에 마지막으로 업데이트했습니다.
7 글 보임 - 1 에서 7 까지 (총 7 중에서)
  • 글쓴이
  • #39486

    유순복
    참가자
    
    선생님 안녕하세요.
    댓글작성까지는 잘 되는데 
    댓글삭제에서 index번호를 못가져와서요.
    
    
    
    
    
    CommentList.jsx 
    
    import React from 'react';
    import Comment from './Comment';
    import { useState } from 'react';
    const CommentList = () => {
    
    
      const [customerList, setCustomerList]= useState([
          {
              id: 1,
              name: "홍길동",
              message:"안녕하세요. 반갑습니다."
          },
          {
              id: 2,
              name: "이순신",
              message:"동해바다가 보여요."
          },
          {
              id: 3,
              name: "광개토대왕",
              message:"함경북도는 얼마나 더 가야하죠?"
          }
      ]);
      
      let count = customerList.length-1
      // let data = setCustomerList;
    
    
      const [customer, setCustomer]=useState({
          id: '',
          name:'', 
          message:'', 
        });
      const handleName = (e)=>{
        // console.log(e.target.value);
       
     
        setCustomer((prevState)=>{
          // return({...prevState, name:e.target.value});
          
          return( { ...prevState, id:++count, name:e.target.value, });
            
        });
      };
      const handleMessage = (e)=>{
    //    console.log(e.target.value);
        setCustomer((prevState)=>{
        return({...prevState, message:e.target.value});
      });
      };
    
    
    
    
      const itemDelete = (e) => {
      
      let copy = [...customerList];
      let btns = document.querySelectorAll('button');
      
      btns.forEach((el, index) => {
      
        el.onclick = (e) => {
          console.log(index);
          copy.splice(index, 1);
          setCustomerList(copy);
        }
      });
      
    };
    
    
      const handleCommit = (e)=>{
      console.log(customer.id);
      console.log(customer.name);
      console.log(customer.message);
    
    
      //추가
        setCustomerList((prevState)=>{
            return [...prevState, customer];
            //앞으로 입력값이 들어감
          //  return [customer,...prevState];
        });
        //input 초기화
        setCustomer(()=>{
            return {name:'', message:''};
        });
      };
        
      // console.log(customerList);
      
      return (
          <div>
              {/* <Comment name={"이순신"} message={"안녕하세요"}/>
              <Comment name={"광개토대왕"} message={"목요일입니다"}/> */}
              
                
              {
            
                customerList.map((customerList, index)=>{
                return(
             
                    <Comment  name={customerList.name} message={customerList.message} itemDelete={itemDelete} i={index} key={index} />
                    
                );
                })
              }
    
    
              
              <div style={{ width:'90%', backgroundColor:'#eee', padding:'20px', margin:'20px'}}>
                  <h4> 댓글을 달아주세요</h4>
                  
                  <p>이름</p>
                  <input type="text" onChange={handleName} value={customer.name} style={{width:'95%', height:'20px'}}></input>
          
                      
                  <p>메시지</p>
                  <input type="text" onChange={handleMessage} value={customer.message} style={{width:'95%', height:'100px'}} placeholder="내용을 입력하세요"></input>
          
          
                  <button onClick={handleCommit} style={{padding:'10px', margin:'10px', backgroundColor:'skyblue', border:'none', display:'block', }}>댓글작성</button>
              </div>
          </div>
      );
    };
    export default CommentList;
    
    
    
    
    
    ------------------------
    Comment.jsx
    
    
    import React from 'react';
    import CommentList  from './CommentList';
    import { useState } from 'react';
    const styles = {
       wrapper :{
        margin:8,
        padding:8,
        display:"flex",
        flexDirection:"row",
        border:"1px solid gray",
        borderRadius:16
       },
       imageContainer: {},
       image : {
         width:50,
         height:50,
         borderRadius:25,
       },
       contextContainer :{
         marginLift:8,
         display:"flex",
         flexDirection:"column",
         justfyContent:"ceter"
       },
       nameText : {
        color:"block",
        fontSize:18,
        fontWeight:"bold",
        marginLeft:"10px"
       },
       commentText: {
        color:"block",
        fontSize:14,
        marginLeft:"10px",
        marginTop:"5px",
       },
       btn:{
        width:'50px',
        height:'30px',
        backgroundColor:'silver',
        opacity:'80%',
        border:'none',
        color:'white',
        marginLeft:'300px'
       }
    };
     
    const Comment = (props) => {
      
        return (
            <div style={styles.wrapper}>
                <div style={styles.imageContainer}>
                   </img>
                </div>
                <div style={styles.contextContainer}>
                    <span style={styles.nameText}>{props.name}</span>
                    <span style={styles.commentText}>{props.message}</span>
               
               
                    {/* <button style={styles.btn}  i={props.index} > 삭제</button> */}
                    <button style={styles.btn} onClick={props.itemDelete}  i={props.index} > 삭제</button>
    
    
                </div>
            </div>
               
    
    
        );
    };
    
    
    
    
    export default Comment
    
    
    
    
    #39500

    codingapple
    키 마스터
    버튼누르면 이벤트리스너 부착하라고 작성해서 그런듯요 
    페이지 로드시나 그럴 때 이벤트리스너 부착해봅시다
    #39505

    조경진
    참가자
    비동기처리 되기 떄문에 status가 늦게 변경이 되기 때문인가요?
    #39519

    codingapple
    키 마스터
    state변경이랑은 상관없습니다 버튼누르면 이벤트리스너 부착해달라고 코드짜서그럴 뿐입니다
    #39659

    유순복
    참가자
    선생님  ^^
    onClick으로 받으면 i값은 받아오고 customerList의  state값을 못가져오고
    
    이벤트 리스너로 받으면  customerList의 state값은 가져오고 i값은 못가져와요
    그래서 이벤트리스너로 하다보니 each 함수를 써서 2번클릭해야 버튼의 index값을 가져오고요
    
    i로   2주째 고민한 거 같아요. 아름다워요.~~
    
    그렇다고 가르쳐주신 리덕스로 하기엔 뭔가 코드가 사치스러운거같기도하고 
    많이 뜯어고쳐야할것같아서 
    엄두가 나지 않아요.
    
    
    #39671

    codingapple
    키 마스터
    버튼에 직접 onClick={()=>{}} 넣어도 됩니다
    #39844

    유순복
    참가자
    선생님 
    익숙한 코드로 하니까 돼요~~
    이코드로 할필요 있냐 싶어서 ㅋ
    아는걸로 해보자하고 만지니까 바로 돼요~
    
    감사합니다. 꾸벅
    
    
    
    
    import {useState} from 'react'
    function App() {
        const [customerList, setCustomerList]= useState([
            {
                id: 1,
                name: "홍길동",
                message:"서울시",
                phone :"안녕하세요. 반갑습니다."
            },
            {
              id: 2,
              name: "이순신",
              message:"동해바다가 보여요."
          },
          {
            id: 3,
            name: "광개토대왕",
            message:"함경북도는 얼마나 더 가야하죠?"
          }
         ]);
        const [customer, setCustomer]=useState({
            id:'', 
            name:'', 
            message:''
          });
        const handleName = (e)=>{
          // console.log(e.target.value);
          setCustomer((prevState)=>{
            return({...prevState, name:e.target.value});
          });
        };
        const handlemessage = (e)=>{
      //    console.log(e.target.value);
         setCustomer((prevState)=>{
          return({...prevState, message:e.target.value});
        });
       };
       const handleCommit = (e)=>{
        console.log(customer.id);
         console.log(customer.name);
         console.log(customer.message);
         //추가
          setCustomerList((prevState)=>{
              // return [...prevState, customer];
              //앞으로 입력값이 들어감
              return [customer,...prevState];
          });
          //input 초기화
          setCustomer(()=>{
              return {id:'', name:'', message:''};
          });
         };
         let style1 = {
          width:"80%",
          border:"1px solid gray",
          padding:"10px",
          borderRadius:"10px",
          backgroundColor:"skyblue",
          padding:"20px",
          margin:"20px"
         }
         let style2 = {
           fontSize: "15px"
         }
      return (
          <>
                <h3>댓글달기</h3>
                 
                    <div>
                    {customerList.map((element,idx)=> {
                     return(
                         <div key={idx}  style = {style1}>
                             <h5>{element.name}</h5>
                             <p>{element.message}</p>
                             <button onClick={()=>{
                                let copy = [...customerList];
                                copy.splice(idx, 1);
                                setCustomerList(copy);
                             }}>삭제</button>
                         </div>
                     );
                     })}
                   </div>
    
    
                    <p>
                    <span> 이름</span>
                    <input type="text" onChange={handleName} value={customer.name}></input>
                    </p>
                    <p>        
                    <span>댓글</span>
                    <input type="text" onChange={handlemessage} value={customer.message}></input>
                    </p>
           
                    <button onClick={handleCommit}>click</button>
            </>
      );
    }
    export default App
    
    
    
    
    
7 글 보임 - 1 에서 7 까지 (총 7 중에서)
  • 답변은 로그인 후 가능합니다.

About

현재 월 700명 신규수강중입니다.

  (09:00~20:00) 빠른 상담은 카톡 플러스친구 코딩애플 (링크)
  admin@codingapple.com
  이용약관, 개인정보처리방침
ⓒ Codingapple, 강의 예제, 영상 복제 금지
top

© Codingapple, All rights reserved. 슈퍼로켓 에듀케이션 / 서울특별시 강동구 고덕로 19길 30 / 사업자등록번호 : 212-26-14752 온라인 교육학원업 / 통신판매업신고번호 : 제 2017-서울강동-0002 호 / 개인정보관리자 : 박종흠