写了个todolist案例代码如下
import React,{Component} from ‘react’
//Todolist容器
export default class TodoList extends Component {
constructor(props) {
super(props)
this.state = {
todos:[‘代欣璐’,‘吃饭’,‘睡觉’,‘打豆豆’],
}
this.handleAdd = this.handleAdd.bind(this)
this.deleteTodo = this.deleteTodo.bind(this)
}
handleAdd(value){
console.log(value)
let todos = this.state.todos.slice()
todos.push(value)
console.log(todos)
this.setState({todos:todos})
}
deleteTodo(index){
console.log(‘fuji’,index)
let todos = this.state.todos.slice()
todos.splice(index,1)
this.setState({todos:todos})
}
render() {
return (
This is TodoList
)
}
}
//添加
class Add extends Component {
constructor(props) {
super(props)
// this.handleClick = this.handleClick.bind(this)
}
handleClick(){
let value = this.input.value;
this.props.onClick(value)
console.log(this.input)
}
render(){
return (
<input type=“text” ref={input=>this.input = input}/>
<button onClick={()=>this.handleClick()}>添加
)
}
}
//展示list
class List extends Component {
constructor(props){
super(props)
}
deleteTodo(index){
this.props.deleteTodo(index)
}
render(){
return (
{this.props.todos.map((item,index)=>{
return (
{item}
<button onClick={()=>this.deleteTodo(index)}>删除
- )
})}
)
}
}
因为刚开始学习React 在我需要点击list中的<button onClick={()=>this.deleteTodo(index)}>删除按钮时 通过传回index值在父组件中
修改this.state.todos
触发的事件为 this.deleteTodo
render() {
return (
This is TodoList
)
}
但我像这样写的时候<list deleteTodo ={()=>this.deleteTodo()}>
handleAdd(value){
console.log(value) //这里输出的undefined
let todos = this.state.todos.slice()
todos.push(value)
console.log(todos)
this.setState({todos:todos})
}
如果写成这样 就能得到正确的index ,这里没怎么想明白,先记住这个错误