react子组件传值给父组件遇到的小问题

写了个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 ,这里没怎么想明白,先记住这个错误

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值