React父子组件传值

父组件TodoList,子组件TodoItem
要实现的是todolist的列表展示和删除
展示部分交给组件TodoItem来做

上代码:

TodoList.js

import React from'react'
import TodoItem from './todoItem'

export default class TodoList extends React.Component{
    constructor(props){
        super(props)
        this.state = {
            inputValue: '',
            list: []
        }
    }
    handleInput = (event) => {
        this.setState({
            inputValue: event.target.value
        })
    }
    handleAdd = () => {
        const list = this.state.list
        list.push(this.state.inputValue)
        this.setState({
            list
        })
    }
    handleItemDel = (index) => {
        const list = this.state.list
        list.splice(index,1)
        this.setState({
            list
        })
    }
    render(){
        return <div>
            <input onChange={this.handleInput}/>
            <button onClick={this.handleAdd}>添加</button>
            <ul>
                {this.state.list.map((item,index)=>{
                    return <li>
                        <TodoItem
                        content={item}
                        index={index}
                        handleItemDel={this.handleItemDel} />
                    </li>
                })}
            </ul>
        </div>
    }
}
TodoItem.js

import React from 'react'

export default class TodoItem extends React.Component{
    handleDel = () => {
        this.props.handleItemDel(this.props.index)
    }
    render(){
        return <div onClick={this.handleDel}>{this.props.content}</div>
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值