7 글 보임 - 1 에서 7 까지 (총 7 중에서)
-
글쓴이글
-
2022년 7월 26일 11:12 #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
2022년 7월 28일 09:18 #39659
유순복참가자선생님 ^^
onClick으로 받으면 i값은 받아오고 customerList의 state값을 못가져오고 이벤트 리스너로 받으면 customerList의 state값은 가져오고 i값은 못가져와요 그래서 이벤트리스너로 하다보니 each 함수를 써서 2번클릭해야 버튼의 index값을 가져오고요 i로 2주째 고민한 거 같아요. 아름다워요.~~ 그렇다고 가르쳐주신 리덕스로 하기엔 뭔가 코드가 사치스러운거같기도하고 많이 뜯어고쳐야할것같아서 엄두가 나지 않아요.
2022년 7월 30일 09:47 #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 중에서)
- 답변은 로그인 후 가능합니다.