父组件
import React, { Component, Fragment } from 'react';
import TodoItem from './todoitem';
// import React from 'react'
// const Component = React.Component
// import style from './style.css'
class Todolist extends Component {
constructor(props) {
super(props);
this.state = {
inputValue: '',
list: []
}
}
handleOnChange(e) {
// console.log("事件目标对象", e.target.value) //获取事情对应的DOM节点对象
// console.log("todolist组建对象",this)
// this.setState({
// inputValue: e.target.value,
// })
//新版 支持一个方法返回一个state对象 变成异步 直接使用会报错
const value = e.target.value;
this.setState(() => ({
// inputValue: e.target.value,
inputValue: value
}));
}
handleSubmit() {
// console.log(this.state.list)
// let todo = this.state.inputValue
//本方法时向数组最后添加元素并返回数组长度 但是直接修改state react 不提倡
// this.state.list.push(todo);
//用展开运算符 解构赋值
// this.setState({
// list: [...this.state.list, todo],
// inputValue: ''
// })
//这样可以接收修改之前的state值 并且改为异步方法
this.setState((preState) => ({
list: [...preState.list, preState.inputValue],
inputValue: ''
}));
}
handleItemDelete(index) {
console.log(index);
//删除index下标的元素,删除1个 不写则删除后面所有 0则是不删除
// immutable 不直接修改state里面的值 react 不提倡
// this.state.list.splice(index,1);
// this.setState({
// list: [...this.state.list],
// })
//不同的设置状态 不太好
// this.setState({
// list,
// });
//改为异步方式 去掉return 注意区别什么时候不用return 用小括号时不用return
// this.setState(() => ({
// list
// }));
//标准的写法
this.setState((preState) => {
const list = [...preState.list];
list.splice(index, 1)
return {list}
});
}
render() {
return (
<Fragment>
<div>
{/*
花括号里面js代码 里面注释就可以安装js的注释方式 注意单行要单独一行 //
*/}
<label htmlFor="insertContent">输入内容:</label>
<input
id="insertContent"
//全局样式不需要引入
className='input'
type="text" value={this.state.inputValue}
// onChange={this.handleOnChange} /> this为undefined 但是会触发handleOnChange
// onChange={this.handleOnChange.bind(this)} /> 可以这样绑定
// onChange={(e) =>this.handleOnChange(e)} /> 用箭头函数 自动绑定
onChange={e => this.handleOnChange(e)} />
<button
// onClick={this.handleSubmit()} 只页面渲染调用方法
onClick={() => this.handleSubmit()}
>提交</button>
</div>
<ul>
{this.getTodoitem()}
</ul>
</Fragment>
);
}
getTodoitem() {
return this.state.list && this.state.list.map((item, index) => {
return <TodoItem
key={index} //外面如果套一层则需要将她放在外面
index={index}
content={item}
//传给子类时必须绑定this到父组件 不然子组件调用时会报错 其实应该放在头部绑定
handleItemDelete={this.handleItemDelete.bind(this)} />
})
}
}
// registerServiceWorker();
export default Todolist
//子组件
import React, { Component } from 'react'
class TodoItem extends Component {
constructor(props) {
super(props);
//将this绑定的todoItem 组件而不是调用的元素 绑定放在页面的头部 否则影响性能
this.handleClick=this.handleClick.bind(this)
}
handleClick(){
//解构赋值
const {index ,handleItemDelete} =this.props
handleItemDelete(index)
}
render() {
//用花括号 包住
const {content} =this.props;
return (
<li onClick={this.handleClick}>{content}</li>
)
}
}
export default TodoItem