2swan
React Practice(2) 본문
App.js
import { Component } from 'react';
import './App.css';
import PhoneList from './component/PhoneList';
import PhoneForm from './component/PhoneForm';
class App extends Component {
id = 2;
state = {
information: [
{
id : 0,
name:"홍길동",
phone:"010-1111-1111"
},
{
id : 1,
name:"이순신",
phone:"010-2222-2222"
}
]
}
//추가(기존 값에 추가)
handleCreate= (data) =>{
console.log(data)
const {information} = this.state
this.setState({
information : information.concat({
id : this.id++, ...data
})
})
}
//삭제
handleRemove = (id) => {
const { information } = this.state;
this.setState({
information: information.filter(info => info.id !== id)
})
}
render(){
return (
<div>
<PhoneForm onCreate = {this.handleCreate}/>
<PhoneList data={this.state.information} onRemove={this.handleRemove}/>
</div>
);
}
}
export default App;
PhoneForm.js
import { Component } from "react"
class PhoneForm extends Component{
state = {
name: '',
phone: ''
}
//추가
handleSubmit = (e) =>{
e.preventDefault();
this.props.onCreate(this.state)
this.setState({
name:'',
phone:''
})
}
//이름, 전화번호 입력시 호출
handleChange = (e) =>{
console.log(e.target.name+":"+e.target.value);
this.setState({
[e.target.name]: e.target.value
})
}
render(){
return(
<div>
<form onSubmit={this.handleSubmit}>
<input placeholder="이름" onChange={this.handleChange} value={this.state.name} name="name"/>
<input placeholder="전화번호" onChange={this.handleChange} value={this.state.phone} name="phone"/>
<button type="submit">등록</button>
</form>
</div>
)
}
}
export default PhoneForm;
PhoneInfo.js
import { Component } from "react"
class PhoneInfo extends Component{
handleRemove = () => {
const { info, onRemove } = this.props;
onRemove(info.id)
}
render(){
const {name, phone, id} = this.props.info;
const style = {
border : '3px solid black',
padding : '8px',
margin : '8px'
}
return(
<div style={style}>
<div>id: {id}</div>
<div>이름: {name}</div>
<div>전화번호: {phone}</div>
<button onClick={this.handleRemove}>삭제</button>
</div>
)
}
}
export default PhoneInfo
PhoneList.js
import {Component} from "react"
import PhoneInfo from "./PhoneInfo"
class PhoneList extends Component{
render(){
const{data, onRemove} = this.props
return(
<div>
[PhoneList~~~]<br/>
{
data.map((info)=>{
return(
<PhoneInfo key={info.id}
info={info} onRemove={onRemove}/>
)
})
}
</div>
)
}
}
export default PhoneList
'Programming > React' 카테고리의 다른 글
React 추가, 삭제(JPA) (0) | 2023.09.11 |
---|---|
React Practice(3) (0) | 2023.09.06 |
React Practice(1) (0) | 2023.09.06 |
React Practice(4-3) (0) | 2023.09.04 |
React Practice(4-2) (0) | 2023.09.04 |