app.js
import React, {Component} from 'react';
import logo from './logo.svg';
import './App.css';
import {Person,Twoway} from './Person/Person'
class App extends Component{
state={
persons:[{name:'小仙女',age:'18'},{name:'小玉',age:'18'},{name:'家璇',age:'18'},{name:'小仙女',age:'18'},{name:'小玉',age:'18'},{name:'家璇',age:'18'}],
name:'',
age:''
}
delete=(index)=>{
console.log(index)
let persons=this.state.persons
//const persons=[...this.state.persons]
persons.splice(index,1) //splice改变的是自身数组的长度,如果用变量接收则是删除项的值
this.setState({
persons:persons
})
}
getname=(event)=>{
console.log(event.target.value); //获取子组件input的值
this.setState({
name:event.target.value
})
}
getage=(event)=>{
console.log(event.target.value); //获取子组件input的值
this.setState({
age:event.target.value
})
}
add=()=>{
console.log(this.state.name)
console.log(this.state.age)
let persons=this.state.persons
// const persons=[...this.state.persons]
persons.push({name:this.state.name,age:this.state.age})
this.setState({
persons:persons,
name:'',
age:''
})
}
render(){
// 遍历数据
const listItems = this.state.persons.map((item,index) =>
<Person name={item.name} age={item.age} key={index} myclick={this.delete.bind(this,index)}/>
);
return(
<div className="App">
{listItems}
<hr></hr>
<input placeholder='请输入名字' onChange={this.getname} value={this.state.name}/>
<input placeholder='请输入年龄' onChange={this.getage} value={this.state.age}/>
<button onClick={this.add}>添加</button>
</div>
)
}
}
export default App;
person.js
import React from 'react';
const Person=(props)=>{
return(
<div>
<p>
我是{props.name},今年{props.age}岁
</p>
<button onClick={props.myclick}>删除</button>
</div>
)
}
const Twoway=(props)=>{
return(
<div>
<p>数据双向绑定</p>
<input type='text' onChange={props.get} placeholder='子组件的input'></input>
</div>
)
}
// export default Twoway
export
{
Person,
Twoway
}