How to get input field value on link click?

白昼怎懂夜的黑 提交于 2021-01-29 21:20:16

问题


I am generating my form dynamically using json.but I struck at one place while getting value of input field on click.

When My demo application run .it shows a input field ( where user enter a mobile number) and a button (text send OTP).After entering number example (9891234178) and press enter it shows OTP field and a link resend OTP .

I want to capture click handler of link (Resend otp) on click I want to get my input field value (mobile number value).

Can It is possible to get value ?

Here is my code https://codesandbox.io/s/react-hook-form-get-started-lokp2

case "link":
  return (
    <div className="form-group">
      <p className="user-link">
        <span onClick={() => {}}> {label}</span>
      </p>
    </div>
  );

my goal is to add click handler of link and try to get mobile number value. if it possible

any update?????/


回答1:


There are two methods you may want to have a read on the documentation:

This function will return the entire form data, and it's useful in a function when you want to retrieve form values. https://react-hook-form.com/api#getValues

This will watch specified input/inputs and return its value, and it's useful for determining what to render. https://react-hook-form.com/api#watch




回答2:


Although I think the form logic is a bit "complicated", you could use the data that returned from onSubmit to pass the values back to your getForm() function.

const App = () => {
  // Create a new `state`
  const [formValues, setFormValue] = useState({})
  //...

  const onSubmit = data => {
    //...
    // assign the form data to the 'formValues' state
    setFormValue(data)
  }

  return (
    <form onSubmit={handleSubmit(onSubmit)} noValidate>
      {!state
        ? getForm(forgetPasswordConfig, register, errors)
        : getForm(
            forgetPasswordAfterSendingOtpConfig,
            register,
            errors,
            formValues // pass back the values
          )}
    </form>
  )
}

Then catch the values like this:

export const getForm = (config, register, errors, formValues) => {

  // Based on `state`, formValues will be available and filled after the user clicks on 
  // the first button "Send OTP" and so, you can get the field value by its name "msisdn"

  case "link":
    return (
      <div className="form-group" key={index}>
        <p className="user-link">
          <span onClick={() => console.log(formValues.msisdn)}> {label}</span>
        </p>
      </div>
    )
}



来源:https://stackoverflow.com/questions/60080728/how-to-get-input-field-value-on-link-click

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!