简体   繁体   English

如何识别在反应中单击了哪个按钮?

[英]how to identify which button clicked in react?

I have two buttons that execute the same function, and that function needs to evaluate go backward or go forward as I show in the following image I have two buttons that execute the same function, and that function needs to evaluate go backward or go forward as I show in the following image

在此处输入图像描述

and in the following code I want to evaluate what function next() or prev() to execute depending on which button was touched, this is built in react在下面的代码中,我想评估 function next() 或 prev() 执行取决于哪个按钮被触摸,这是内置的反应

const onFinish = (values) => {常量 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(); };

and in this form I pass by parameter the function在这种形式下,我通过参数传递 function

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

You can identify them by assigning unique Id to both button like this您可以通过为这两个按钮分配唯一 ID 来识别它们

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

And in you listener check id which button clicked.在你的听众中检查点击了哪个按钮。

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

I don't know the parameters that you got on that custom buttons and how is it triggering onClick event.我不知道您在自定义按钮上获得的参数以及它如何触发 onClick 事件。 But here is the solution for HTML buttons.但这里是 HTML 按钮的解决方案。

You can set a value to the button like this.您可以像这样为按钮设置一个值。

<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()
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM