//父组件:
import React, { Component, Fragment } from 'react';
import Home from './App.test'
import './App.css';
class App extends Component {
constructor(props) {
super(props)
this.state = {
inputValue: '',
list: ['js' ,'css']
}
}
render() {
return (
<Fragment>
<div>
<label>增加服务</label>
<input value={this.state.inputValue} onChange={this.inputChange.bind(this)}/>
<button onClick={this.addLsit.bind(this)}>增加</button>
</div>
<ul>
{
this.state.list.map((item,index)=>{
return (
<Home
key={index+item}
content={item}
index={index}
deleteItem={this.deleteItem.bind(this)} />
)
})
}
</ul>
</Fragment>
)
}
inputChange(e){
this.setState({
inputValue:e.target.value
})
}
//增加列表:
addLsit(){
this.setState({
list:[...this.state.list,this.state.inputValue],
inputValue:''
})
}
//删除列表项:
deleteItem(index){
let list = this.state.list
list.splice(index,1)
this.setState({
list:list
})
}
}
export default App;
//子组件:
import React, { Component, Fragment } from 'react';
import PropTypes from 'prop-types'
class Home extends Component {
constructor(props){
super(props)
this.hadleClick = this.hadleClick.bind(this)
}
render() {
return (
<li onClick={this.hadleClick}>{this.props.avname}{this.props.content}</li>
)
}
hadleClick(){
console.log(this.props.index)
this.props.deleteItem(this.props.index)
}
}
Home.propTypes={
avname:PropTypes.string.isRequired,
content:PropTypes.string,
index:PropTypes.number,
deleteItem:PropTypes.func
}
Home.defaultProps={
avname: '项目'
}
export default Home;
网友评论