728x90
프로젝트 중심
-----------------------------------------------------------------------------------------------------
게시판 관련 components(Board, BoardList, BoardDetail, ...) 기능 구현 중
게시판 관련 컴포넌트들의 기능을 연동하는 과정을 거쳤다.
BoardDetail 컴포넌트 - 게시글 상세보기 기능
import React, { Component } from 'react';
import '../../css/Board/BoardDetail.css';
import axios from 'axios';
class BoardDetail extends Component {
constructor(props) {
super(props);
const { board } = props;
this.state = {
showEditForm: false,
title: board.title,
contents: board.contents,
writer: board.writer,
writeDate: board.writeDate,
};
}
handleBackClick = () => {
const { onBack } = this.props;
if (onBack) {
onBack();
}
};
handleEditClick = () => {
this.setState((prevState) => ({
showEditForm: !prevState.showEditForm,
}));
};
handleDeleteClick = () => {
const { board, onDelete } = this.props;
axios
.delete(`/board/${board.no}`)
.then((response) => {
alert('게시글이 삭제되었습니다.');
onDelete(board.no); // 삭제된 게시글의 ID를 상위 컴포넌트로 전달
console.log('Board deleted successfully:', response.data);
})
.catch((error) => {
console.error('Error deleting board:', error);
});
};
handleInputChange = (e) => {
const { name, value } = e.target;
this.setState({ [name]: value });
};
handleUpdateClick = () => {
const { board, onUpdate } = this.props;
const { title, contents, writer, writeDate } = this.state;
const updatedBoard = { ...board, title, contents, writer, writeDate };
axios
.put(`/board/${board.no}`, updatedBoard)
.then((response) => {
alert('게시글이 수정되었습니다.');
onUpdate(updatedBoard); // 수정된 게시글 정보를 상위 컴포넌트로 전달
this.setState({ showEditForm: false });
console.log('Board updated successfully:', response.data);
})
.catch((error) => {
console.error('Error updating board:', error);
});
};
componentDidMount() {
// 게시글 목록 데이터를 서버에서 가져와 설정
axios
.get('/board')
.then((response) => {
this.setState({
boardList: response.data,
});
console.log('Board list retrieved successfully:', response.data);
})
.catch((error) => {
console.error('Error retrieving board list:', error);
});
}
render() {
const { board } = this.props;
const { showEditForm, title, contents, writer, writeDate } = this.state;
if (!board) {
return <div>Loading...</div>;
}
return (
<div id="board-detail">
{showEditForm ? (
<form id='re-board'>
<div id='re-title'>
<label htmlFor="title">제목:</label>
<input
type="text"
id="title"
name="title"
value={title}
onChange={this.handleInputChange}
/>
</div>
<div id='re-contents'>
<label htmlFor="contents">내용:</label>
<textarea
id="contents"
name="contents"
value={contents}
onChange={this.handleInputChange}
></textarea>
</div>
<div id='re-writer'>
<label htmlFor="writer">작성자:</label>
<input
type="text"
id="writer"
name="writer"
value={writer}
onChange={this.handleInputChange}
/>
</div>
<div id='re-writeDate'>
<label htmlFor="writeDate">작성일:</label>
<input
type="date"
id="writeDate"
name="writeDate"
value={writeDate}
onChange={this.handleInputChange}
/>
</div>
<button onClick={this.handleUpdateClick}>확인</button>
<button onClick={this.handleEditClick}>취소</button>
</form>
) : (
<>
<div id="title">{board.title}</div>
<div id="contents">{board.contents}</div>
<div id="writer">{board.writer}</div>
<div id="writeDate">{board.writeDate}</div>
<button onClick={this.handleBackClick}>뒤로 가기</button>
<button onClick={this.handleEditClick}>수정</button>
<button onClick={this.handleDeleteClick}>삭제</button>
</>
)}
</div>
);
}
}
export default BoardDetail;
BoardList 컴포넌트
import React, { Component } from "react";
import '../../css/Board/BoardList.css';
import TakeBoard from "./TakeBoard.js";
import BoardDetail from "./BoardDetail.js";
class BoardList extends Component {
constructor(props) {
super(props);
this.state = {
selectedBoard: null,
showBoardDetail: false,
boardList: props.boardList || [],
};
}
handleBoardClick = (board) => {
this.setState({
selectedBoard: board,
showBoardDetail: true,
});
};
handleBack = () => {
this.setState({
showBoardDetail: false,
});
};
handleDelete = (boardNo) => {
// 게시글 삭제 후 목록 갱신
this.setState((prevState) => ({
boardList: prevState.boardList.filter((board) => board.no !== boardNo),
}));
};
handleUpdate = (updatedBoard) => {
// 게시글 수정 후 목록 갱신
this.setState((prevState) => ({
boardList: prevState.boardList.map((board) =>
board.no === updatedBoard.no ? updatedBoard : board
),
}));
};
componentDidUpdate(prevProps) {
if (prevProps.boardList !== this.props.boardList) {
this.setState({
boardList: this.props.boardList,
});
}
}
render() {
const { boardList, selectedBoard, showBoardDetail } = this.state;
if (showBoardDetail) {
return (
<div id="board-list">
<BoardDetail
board={selectedBoard}
onBack={this.handleBack}
onDelete={this.handleDelete}
onUpdate={this.handleUpdate}
/>
</div>
);
}
const result = boardList.map((data) => (
<TakeBoard
key={data.no}
no={data.no}
title={data.title}
writer={data.writer}
writeDate={data.writeDate}
onClick={() => this.handleBoardClick(data)}
/>
));
return (
<div id="board-list">
<div id="list-header">
<TakeBoard
no="번호"
title="제목"
writer="글쓴이"
writeDate="글쓴날짜"
/>
</div>
{result}
</div>
);
}
}
export default BoardList;
TakeBoard 컴포넌트
import React from 'react';
import '../../css/Board/TakeBoard.css';
const TakeBoard = (props) => {
const handleClick = () => {
props.onClick({
no: props.no,
title: props.title,
writer: props.writer,
writeDate: props.writeDate,
});
};
return (
<div id="takeboard" onClick={handleClick}>
{/* <span>{props.no}</span> */}
<span>{props.title}</span>
<span>{props.writer}</span>
<span>{props.writeDate}</span>
</div>
);
};
export default TakeBoard;
NewBoard 컴포넌트
import '../../css/Board/NewBoard.css';
import React, { Component } from "react";
import axios from "axios";
class NewBoard extends Component {
constructor(props) {
super(props);
this.state = {
newTitle: "",
newContents: "",
newWriter: "",
newWriteDate: "",
};
}
handleCreateBoard = () => {
const { newTitle, newContents, newWriter, newWriteDate } = this.state;
axios
.post("/board", {
title: newTitle,
contents: newContents,
writer: newWriter,
writeDate: newWriteDate,
})
.then((response) => {
console.log("Board created:", response.data);
this.props.fetchBoardList(); // Board 컴포넌트의 fetchBoardList 메서드 호출
this.resetForm();
})
.catch((error) => {
console.error("Error creating board:", error);
});
};
handleDeleteBoard = (no) => {
axios
.delete(`/board/${no}`)
.then((response) => {
console.log("Board deleted:", response.data);
this.props.fetchBoardList(); // Board 컴포넌트의 fetchBoardList 메서드 호출
})
.catch((error) => {
console.error("Error deleting board:", error);
});
};
resetForm = () => {
this.setState({
newTitle: "",
newContents: "",
newWriter: "",
newWriteDate: "",
});
};
handleInputChange = (event) => {
const { name, value } = event.target;
this.setState({ [name]: value });
};
render() {
const { newTitle, newContents, newWriter, newWriteDate } = this.state;
return (
<div id="new-board">
<h3>새 글 작성</h3>
<div id="new-title">
<label htmlFor="newTitle">제목:</label>
<input
type="text"
id="newTitle"
name="newTitle"
value={newTitle}
onChange={this.handleInputChange}
/>
</div>
<div id="new-contents">
<label htmlFor="newContents">내용:</label>
<textarea
id="newContents"
name="newContents"
value={newContents}
onChange={this.handleInputChange}
></textarea>
</div>
<div id="new-writer">
<label htmlFor="newWriter">작성자:</label>
<input
type="text"
id="newWriter"
name="newWriter"
value={newWriter}
onChange={this.handleInputChange}
/>
</div>
<div id="new-writeDate">
<label htmlFor="newWriteDate">작성일:</label>
<input
type="date"
id="newWriteDate"
name="newWriteDate"
value={newWriteDate}
onChange={this.handleInputChange}
/>
</div>
<div id="SCbutton">
<button onClick={this.handleCreateBoard}><a href="/board">저장</a></button>
<button onClick={this.resetForm}><a href="/board">취소</a></button>
</div>
</div>
);
}
}
export default NewBoard;
728x90