( 父组件TodoList.js)
import React, {Component,Fragment} from 'react';
import './style.css';
import TodoItem from './TodoItem';
class TodoList extends Component {
// 当我们使用组件的时候,constructor函数优于其他任何函数自动的最先被执行
constructor(props) {
//super指的是调用父类的构造函数,继承经常要做的事情
super(props);
//react定义数据定义在状态里
this.state = {
inputValue: '',
list: []
}
}
render() {
return (
<Fragment>
{/*{下面是一个input框}*/}
<div>
<label htmlFor="insertArea">输入内容</label>
<input
id={'insertArea'}
className={'input'}
value={this.state.inputValue}
onChange={this.handleInputChange.bind(this)}
/>
<button
onClick={this.handleButtonClick.bind(this)}
>提交</button>
</div>
<ul>
{
this.state.list.map((item,index)=>{
// item是每一项的内容
// 在react里,当你做循环渲染的时候,需要给渲染出的每一项增加一个key值,这个key值每一项都应该不同,应该是每一项的标识符
return (
<div>
<TodoItem
content={item}
index={index}
deleteItem = {this.handleItemDelete.bind(this)}
/>
</div>
)
})
}
</ul>
</Fragment>
)
}
//每次输入框内输入东西,e作为事件对象会每次都输出来
handleInputChange(e) {
//react给每个组件提供了setState这个方法,如果想改变state里的数据,必须调用这个方法
this.setState({
inputValue: e.target.value
})
}
handleButtonClick(){
this.setState({
list: [...this.state.list,this.state.inputValue],
inputValue:''
})
}
handleItemDelete(index){
//immutable
//state不允许我们做任何的改变,拷贝一个副本出来
const list = [...this.state.list];
list.splice(index,1);
this.setState({
list:list
})
}
}
export default TodoList;
( 子组件TodoItem.js)
import React,{Component} from 'react';
class TodoItem extends Component{
constructor(props){
super(props);
//如果不bind,this指向会指向undefined;这样写页面性能较好
this.handleClick = this.handleClick.bind(this);
}
render() {
return (
<div onClick={this.handleClick}>{this.props.content}</div>
)
}
handleClick(){
// 子组件被点击的时候,调用父组件传过来的deleteItem这个方法,同时把父组件传递过来的index以参数的形式传给这个方法
this.props.deleteItem(this.props.index);
}
}
export default TodoItem;