5. react 基础 - 组件拆分 和 组件传值

1.将 todoList 进行拆分

  创建 编写TodoList.js

import React, {Component, Fragment} from 'react';
import TodoItem from './TodoItem';
class TodoList extends Component {
constructor(props) {
super(props);
this.state = {inputValue: '', list: []}
this.inputChange = this.inputChange.bind(this);
this.itemDelete = this.itemDelete.bind(this);
this.addClick = this.addClick.bind(this);
}
render() {
return (
<Fragment>
<input type='text' value={this.state.inputValue} onChange={this.inputChange}/>
<button onClick={this.addClick}>提交</button>
<ul>
{/*获取 子项*/}
{this.getItem()}
</ul>
</Fragment>
);
}
getItem() {
return this.state.list.map((value, index) => {
/*key 属性 应该加在 最外层 元素上*/
return (
<TodoItem key={index} value={value} index={index} itemDelete={this.itemDelete}/>
);
})
}
inputChange(e) {
const value = e.target.value;
// 异步 的 setState
this.setState(() => ({
inputValue: value
}));
}
addClick() {
const value = this.state.inputValue;
if (!value) return;
// prevState 表示 改变 state 之前的 state 值
this.setState((prevState) => ({
list: [...prevState.list, prevState.inputValue],
inputValue: ''
}))
}
itemDelete(index) {
this.setState((prevState) => {
const list = [...prevState.list];
list.splice(index, 1);
// 形如 return {list:list}
return {list};
})
}
}
export default TodoList;

    

创建 编写TodoItem.js

  #TodoItem.js

import React , { Component } from 'react';
class TodoItem extends Component{
constructor(props){
super(props);
this.delete = this.delete.bind(this);
}
render() {
const {value} = this.props;
return (
<div onClick={this.delete}>{value}</div>
);
}
delete(){
const {itemDelete , index} = this.props;
itemDelete(index);
}
}
export default TodoItem;
 
posted @ 2019-09-30 18:44  zonehoo  阅读(373)  评论(0编辑  收藏  举报