//父组件
import React,{Component} from 'react';
import Register from './register.js';
import List from './list.js';
class App extends Component{
constructor(props){
super(props)
this.state={
obj: [
{name:'张三',age: 18,gender: '男',phone: '18817800121'},
{name:'李四',age: 17,gender: '女',phone: '18817800121'},
{name:'王五',age: 16,gender: '男',phone: '18817800121'},
]
}
}
render(){
let list= this.state.obj;
return(
<div>
<Register list={list} pfn={(data)=>this.fn(data)}/>
<List list={list}/>
</div>
)
}
fn(data){
this.setState({
obj: data
})
}
}
export default App
// 子组件
import React, { Component } from 'react';
import './register.css'
class Register extends Component{
constructor(props){
super(props);
this.state={
name: '',
age: '',
gender: '女',
phone: '',
addDate: this.props.list
}
// let {name,age,gender,phone}=this.state;
}
render(){
let {name,age,gender,phone}=this.state;
return (
<div className="register">
<fieldset>
<legend>表单</legend>
<div>
<span>姓名:</span>
<input placeholder="请输入姓名" value={name} onChange={(e)=>this.changeName(e)}/>
</div>
<div>
<span>年龄:</span>
<input placeholder="请输入年龄" value={age} onChange={(e)=>this.changeAge(e)}/>
</div>
<div>
<span>性别:</span>
<select value={gender} onChange={(e)=>this.changeGender(e)}>
<option value="男">男</option>
<option value="女">女</option>
</select>
</div>
<div>
<span>手机:</span>
<input placeholder="请输入手机号" value={phone} onChange={(e)=>this.changePhone(e)}/>
</div>
<div>
<button onClick={()=>this.addUser()}>添加新用户</button>
</div>
</fieldset>
</div>
)
}
addUser(){
if(this.state.name!='' || this.state.age!='' || this.state.phone!=''){
this.state.addDate.unshift({name: this.state.name,age: this.state.age,gender: this.state.gender,phone:this.state.phone});
this.setState({});
this.props.pfn(this.state.addDate)//这个地方把值传递给了props的事件当中
}else {
alert('数据不能为空')
}
}
changeName(e){
this.setState({
name: e.target.value
})
}
changeAge(e){
this.setState({
age: e.target.value
})
}
changeGender(e){
this.setState({
gender: e.target.value
})
}
changePhone(e){
this.setState({
phone: e.target.value
})
}
}
export default Register