list列表
import React, { Component, Fragment } from "react";
import ItemChild from "./components/ItemChild";
class Xiaojiejie extends Component {
constructor(props) {
super(props);
this.state = {
inputValue: "",
list: ["测试", "aa1"],
};
this.inputChange = this.inputChange.bind(this);
this.addItem = this.addItem.bind(this);
this.deleteItem = this.deleteItem.bind(this);
}
render() {
return (
<Fragment>
<div>
<input
placeholder="请输入服务项目"
onChange={this.inputChange}
value={this.state.inputValue}
/>
<button onClick={this.addItem}> 增加服务 </button>
</div>
<ul>
{this.state.list.map((item, index) => {
return (
<ItemChild
key={item + index}
index={index}
content={item}
deleteItem={this.deleteItem}
></ItemChild>
);
})}
</ul>
</Fragment>
);
}
inputChange(e) {
this.setState({
inputValue: e.target.value,
});
}
addItem() {
this.setState({
list: [...this.state.list, this.state.inputValue],
});
}
deleteItem(index) {
let list = this.state.list;
list.splice(index, 1);
this.setState({
list: list,
});
}
}
export default Xiaojiejie;
item子组件
import React, { Component, Fragment } from "react";
import ProTypes from "prop-types";
class ItemChild extends Component {
constructor(props) {
super(props);
this.handleClick = this.handleClick.bind(this);
}
render() {
return (
<Fragment>
<li onClick={this.handleClick}>{this.props.content}</li>
</Fragment>
);
}
handleClick() {
this.props.deleteItem(this.props.index);
}
}
ItemChild.propTypes = {
content: ProTypes.string,
deleteItem: ProTypes.func,
index: ProTypes.number,
};
export default ItemChild;