【问题标题】:Calling two different functions from onKeyDown event从 onKeyDown 事件调用两个不同的函数
【发布时间】:2018-01-11 13:10:12
【问题描述】:

通过下面的代码,我试图在 ReactJS 应用程序中使用 onKeyDown 事件调用两个不同的函数。

但它没有调用任何这些功能。但是,它只需一个函数调用就可以正常工作。

<input name="product_quantity"
       type="text"
       onKeyDown={ (event) => { 
           this.props.handleInputNumber; 
           this.handleQuantity; } } 
       value={ this.state.item.product_quantity }
       className="form-control"
/>

【问题讨论】:

  • (event) =&gt; { this.props.handleInputNumber(event); this.handleQuantity(event); }
  • 您确定不需要event 参数...?
  • 不,你是对的,。没有事件它不会工作。

标签: javascript reactjs


【解决方案1】:

您缺少括号。此外,您应该将event 至少传递给其中一个函数,或者在不需要时将其删除。

例如 event =&gt; this.props.handleInputNumber(event); this.handleQuantity(event);

【讨论】:

  • 就像在另一个答案中一样,此解决方案不会传递 event 参数。鉴于这是关于处理按键,这样做似乎很有用。
【解决方案2】:
<td>
   <input name="product_quantity" type="text" 
          onKeyDown={(event) => { 
             this.props.handleInputNumber(); this.handleQuantity(); 
          }} 
          value={this.state.item.product_quantity} 
          className="form-control" /></td>

【讨论】:

  • 当然,你没有通过event。
  • @ChrisG ,看问题,这种情况下不需要传递事件参数
  • @KentV,要么在这些函数中使用 event,要么从参数中删除它。我们不知道这两个函数的定义以及是否使用了事件。
  • @ChrisG ,问题仅询问函数调用问题,与事件对象无关。还有一些情况下,当您不需要它时,您不必传递事件参数。
  • @KentV 很可能 OP 以前有 onKey={this.props.handleInputNumber} 或类似的东西,它传递参数。用突然不传递参​​数的两次调用版本替换它,特别是考虑到其中一个是按键处理程序,似乎很麻烦。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-09-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多