react给子组件传递一个函数的时候,子组件如何增加参数?

父组件

  handleIO = (id, type) => {
    console.log(id, type)
  }

<div className={style['bottom-right']}>
    <NumberController num={e.num} handleBtn={()=>this.handleIO(e.id)}/>
</div>

子组件

<span onClick={()=>handleBtn('decrease')} className={style.decrease}></span>
  <span className={style.num}>{num}</span>
<span onClick={()=>handleBtn('increase')} className={style.increase}></span>

父组件传递给子组件的入参为id, 子组件根据不同的按钮触发 分别加上不同的状态参数

类似vue中 $event这种, 该如何实现呢

阅读 3.6k
3 个回答

第一种方法,改handleIO

handleIO = id => type => {
  console.log(id, type)
}

<div className={style['bottom-right']}>
    <NumberController num={e.num} handleBtn={this.handleIO(e.id)}/>
</div>

第二种方法,改handleBtn

handleIO = (id, type) => {
  console.log(id, type)
}

<div className={style['bottom-right']}>
    <NumberController num={e.num} handleBtn={(type)=>this.handleIO(e.id,type)}/>
</div>

或者像楼上写的,把需要的数据全部传入子组件.

<NumberController num={e.num} id={id} handleBtn={this.handleIO}/>
<span onClick={()=>this.props.handleBtn(this.props.id,'decrease')} className={style.decrease}></span>

父组件往子组件传递事件,子组件触发时,父组件接收子组件触发事件传递过来的参数?

  • 父组件:
  handleIO = (id, type) => {
    // 这里就是子组件传过来的两个参数
    console.log(id, type)
  }

<div className={style['bottom-right']}>
    <NumberController num={e.num} id={id} handleBtn={this.handleIO}/>
</div>
  • 子组件
<span onClick={()=> this,props.handleBtn(this.props.id, 'decrease')} className={style.decrease}></span>
  <span className={style.num}>{num}</span>
<span onClick={()=>this,props.handleBtn(this.props.id, 'increase')} className={style.increase}></span>
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题