카테고리 없음
[Project2][React] 컴포넌트
321
2021. 5. 28. 13:50
아래와 같이 컴포넌트들이랑 js파일 생성해준다.
스프링에서 썼던 타일즈는 설정과 문법이 어려웠는데 리액트 컴포넌트를 사용하면 쉽게 사용할 수 있다.
- App.js
// eslint-disable-next-line
import './App.css';
import {BrowserRouter as Router, Route, Switch} from 'react-router-dom';
import ListGoodsComponent from './components/ListGoodsComponent';
import HeaderComponent from './components/HeaderComponent';
import FooterComponent from './components/FooterComponent';
import CreateGoodsComponent from './components/CreateGoodsComponent';
import UpdateGoodsComponent from './components/UpdateGoodsComponent';
import ViewEmployeeComponent from './components/ViewEmployeeComponent';
function App() {
return (
<div>
<Router>
<div className="container">
<HeaderComponent/>
<div className="container">
<Switch>
<Route path="/" exact component={ListGoodsComponent}></Route>
<Route path="/goods" component={ListGoodsComponent}></Route>
<Route path="/add-goods/:id" component={CreateGoodsComponent}></Route>
<Route path="/view-goods/:id" component={ViewEmployeeComponent}></Route>
{/* <Route path="/update-goods/:id" component={UpdateGoodsComponent}></Route> */}
</Switch>
</div>
<FooterComponent/>
</div>
</Router>
</div>
);
}
export default App;
- ListGoodsComponent.jsx
import React, { Component } from 'react';
import GoodsService from '../services/GoodsService';
class ListGoodsComponent extends Component {
constructor(props){
super(props)
this.state={
goods : []
}
//bind
this.addGoods = this.addGoods.bind(this);
this.editGoods = this.editGoods.bind(this);
this.deleteGoods = this.deleteGoods.bind(this);
}
//history.push
editGoods(id){
this.props.history.push(`/add-goods/${id}`);
}
addGoods(){
this.props.history.push('/add-goods/-1');
}
viewGoods(id){
this.props.history.push(`/view-goods/${id}`);
}
//res
componentDidMount(){
GoodsService.getGoods().then((res)=>{
this.setState({goods : res.data});
});
}
deleteGoods(id){
GoodsService.deleteGoods(id).then(res => {
this.setState({goods:this.state.goods.filter(gds => gds.id!==id)});
});
}
render() {
return (
<div>
<h2 className="text-center">Goods List</h2>
<button className="btn btn-primary" onClick={this.addGoods}>ADD GOODS</button>
<div className="row">
<table className="table table-striped table-bordered">
<thead>
<tr>
<th>Goods Name</th>
<th>Goods Company</th>
<th>Goods Price</th>
<th>Action</th>
</tr>
</thead>
<tbody>
{
this.state.goods.map(
gds=>
<tr key={gds.id}>
<td>{gds.name}</td>
<td>{gds.company}</td>
<td>{gds.price}</td>
<td>
<button className="btn btn-info" onClick={()=>this.editGoods(gds.id)}>UPDATE</button>
<button className="btn btn-danger" onClick={()=>this.deleteGoods(gds.id)} style={{marginLeft:"10px"}}>DELETE</button>
<button className="btn btn-primary" onClick={()=>this.viewGoods(gds.id)} style={{marginLeft:"10px"}}>VIEW</button>
</td>
</tr>
)
}
</tbody>
</table>
</div>
</div>
);
}
}
export default ListGoodsComponent;