react-组件之间的传参

父向子传参

父组件向子组件传参时用属性的方式传递
子组件接收的时候用props调用
子组件不能直接改父组件的变量值

  1. 父组件实例如下:
import React,{Component,Fragment}from 'react'
import TodoItemList from './TodoItemList'
class TodoList extends Component{
    constructor(poprs){
     super(poprs);
     this.state={
         inputValue:'',
         list:['学习英文','学习数字']
     }
    }
    render(){
        return (
            <Fragment>
                <div>
                    <input type="text"
                           value={this.state.inputValue}
                           onChange={this.handleInputChange.bind(this)}
                    />
                    <button onClick={this.handleButtonClick.bind(this)}>提交</button>
                </div>
                <ul>
                    {
                        this.state.list.map((item,index)=>{
                            // 父传子 属性传输
                           return (
                               <TodoItemList
                                   key={index}
                                   item={item}
                                   index={index}
                                   DelItem={this.handleDelList.bind(this)}
                               >
                               </TodoItemList>
                           )
                        })
                    }
                </ul>
            </Fragment>
        )
    }
    handleInputChange(e){
     this.setState({
         inputValue:e.target.value
     })
    }
    handleButtonClick(){
      this.setState({
          list:[...this.state.list,this.state.inputValue],
          inputValue:''
      })
    }
    handleDelList(index){
        var list=[...this.state.list]
        list.splice(index,1)
        this.setState({
            list:list
        })
    }
}
export default TodoList;
  1. 子组件实例如下:
import React,{Component,Fragment}from 'react'

class TodoItemList extends Component{
    constructor(props){
        super(props)
    }
    render(){
        return(
            <Fragment>
                <div onClick={this.handleItemClick.bind(this)}>{this.props.item}</div>
            </Fragment>
        )
    }
    handleItemClick(){
        const  {DelItem,index}=this.props
        DelItem(index)
    }
}
export default TodoItemList
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值