You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在InputTime组件的onRemove中传递带参数的remove函数?

问题原因

  • 父组件传入remove属性时没有接收参数的占位,子组件调用remove(i)时传入的索引会被直接丢弃,无法传递到handlerRemove中
  • 若Component是在map遍历中批量渲染,需要确保循环变量i的作用域独立,同时子组件要能正确拿到对应项的索引值
  • 额外注意handlerRemove的this指向是否正确,避免调用时报错

修正代码

父组件修改

// 定义handler时接收索引参数
handlerRemove(index){
  // 此处编写删除逻辑
  console.log('待删除项索引:', index)
}
render() {
  return (
    // 透传参数给handler,也可以简写为remove={this.handlerRemove.bind(this)}
    <Component remove={(i) => this.handlerRemove(i)} />
    // 如果是map遍历渲染多个组件,写法如下:
    // {list.map((item, index) => (
    //   <Component 
    //     key={item.id} 
    //     i={index} // 把当前项索引传给子组件
    //     remove={(i) => this.handlerRemove(i)} 
    //   />
    // ))}
  )
}

子组件修改

render() {
  // 要先拿到props传入的索引i
  const {remove, i} = this.props;
  return(
    <>
        <InputTime
          // 这里的调用写法不需要改动
          onRemove={() => remove(i)}
          {...this.props}
        />
    </>
  )
}

内容的提问来源于stack exchange,提问作者Renan Fernandes

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.03 01:15:04