【问题标题】:how can I pass my remove function with a parameter inside InpuTime?如何在 InpuTime 中传递带有参数的删除函数?
【发布时间】:2021-09-25 03:03:33
【问题描述】:

我正在尝试使用参数将删除函数传递到地图中,但这就像我没有使用我的函数一样。在 onRemove 的 InputTime 中调用“remove(i)”的正确方法是什么?

Component
    
    render() {
    const {remove} = this.props;

    return(
      <>
          <InputTime
            onRemove={() => remove(i)}
            {...this.props}
          />
      </>
    )
  }
}

// another class
  handlerRemove(){
    ...
  }
return(
   <Component remove={() => this.handlerRemove()} />
)

【问题讨论】:

    标签: javascript reactjs typescript react-native


    【解决方案1】:

    给你一个解决方案

    render() {
        const {remove} = this.props;
    
    
        return(
          <>
            
                <InputTime
                  time={hour}
                  onRemove={() => remove(i)}
                  {...this.props}
                />
             
          </>
        )
      }
    }
    

    由于你已经使用const {values, remove} = this.props;完成了破坏,所以你不需要为prop函数添加this

    当前代码onRemove={() =&gt; this.remove(i)}

    将您的代码更改为onRemove={() =&gt; remove(i)}

    当用户稍微更改代码时,基于该解决方案

    Component
        
        render() {
        const {remove} = this.props;
        const arg = "test";
    
        return(
          <>
              <InputTime
                onRemove={() => remove(arg)}
                {...this.props}
              />
          </>
        )
      }
    }
    
    // another class
      handlerRemove(passedArg){
        console.log("passedArg", passedArg);
      }
    return(
       <Component remove={this.handlerRemove} />
    )
    

    【讨论】:

    • 有趣的解释,谢谢。我已经尝试过这种方法,但没有奏效。我将函数从一个类传递给这个类,如下所示:
    • @RenanFernandes 添加一些更改,看看
    • 谢谢,但我的问题仍未解决。如果我的 handleRemove 函数接收到一个参数,我将如何通过 onRemove 发送它? @Shiladitya
    猜你喜欢
    • 2014-09-03
    • 2012-12-11
    • 2013-04-09
    • 2020-06-03
    • 1970-01-01
    • 2021-10-08
    • 2010-11-20
    相关资源
    最近更新 更多