【问题标题】:how to identify which button clicked in react?如何识别在反应中单击了哪个按钮?
【发布时间】:2021-04-25 02:45:20
【问题描述】:

我有两个执行相同功能的按钮,并且该功能需要评估后退或前进,如下图所示

在下面的代码中,我想根据被触摸的按钮来评估要执行的 next() 或 prev() 函数,这是内置的 react

const onFinish = (值) => {

if (values.users) {
  const Operator = values.users.map((item) => ({
    ruleAttributeName: item.ruleAttributeName,

    isoAttributeId: item.isoAttributeId,

    ruleOperationId: item.ruleOperationId,

    mandatoryValue: item.mandatoryValue,
  }));
  setAttributes(Operator);
}
if (values.users) {
  const attributesSave = values.users.map((item) => ({
    ruleAttributeName: item.ruleAttributeName,
    isoAttributeEntity: {
      isoAttributeId: item.isoAttributeId,
    },
    ruleOperationEntity: {
      ruleOperationId: item.ruleOperationId,
    },
    mandatoryValue: item.mandatoryValue,
  }));
  console.log('mandatory';
  setAttributesSave(attributesSave);
  setMandatoryValue();
  next();
  prev();
   };

在这种形式下,我通过参数传递函数

<Form
  name='dynamic_form_nest_item'
  onFinish={onFinish}
  autoComplete='off'
>

【问题讨论】:

  • 将实际代码放在您的问题中,而不是图像中。所以更容易复制你的代码并根据它给出答案
  • 为每个按钮分配一个唯一的 id。在您的onFinish 函数中,将它们标识为event.target.ideven 变量将自动从按钮传递给它。
  • 我已经修改了

标签: javascript reactjs ant-design-pro


【解决方案1】:

我不知道您在自定义按钮上获得的参数以及它是如何触发 onClick 事件的。但这里是 HTML 按钮的解决方案。

您可以像这样为按钮设置一个值。

<button onClick={onFinish} value="next">Next</button>

const onFinish = (ev) => {
  ev.preventDefault() // this is to prevent the refresh
  
  const { value } = ev.target // equals with const value = ev.target.value
  if(value === "next") {
    next()
  } else {
    prev()
  }
}

【讨论】:

    【解决方案2】:

    您可以通过为这两个按钮分配唯一 ID 来识别它们

    <button onClick={onFinish} Id={'1'}>Next</button>
    <button onClick={onFinish} Id={'2'}>Next</button>
    

    在你的监听器中检查点击了哪个按钮。

    const onFinish = (event) => {
      Let id = event.target.id;
      if(id=== "1") {
        // Do for one
      } else {
        // For second
      }
    }
    

    【讨论】:

      猜你喜欢
      • 2012-05-23
      • 2018-05-15
      • 1970-01-01
      • 2017-07-24
      • 2014-01-05
      • 1970-01-01
      • 2012-08-30
      • 1970-01-01
      • 2020-05-09
      相关资源
      最近更新 更多