问题
Is there a way to get the value of a field inside a click handler in formik?
You can use setFieldValue
in there, so I'd assume (but can't find anywhere) that Formik should have something like that for retrieving values:
<Button onClick={() => getFieldValue('name') === 'Test' ? action1 : action2}
What is the correct way to do this in Formik?
回答1:
Formik passes its values
object into your form via props
. Imagine you have an input, wired into Formik under the name firstName
. You can access the input's value via this.props.values.firstName
:
<button onClick={() => console.log(this.props.values.firstName)}>
Log firstName
</button>
I've test this and verified. It's also demonstrated in several places in the documentation.
回答2:
You can access the value of field that you initialize in initalValues through props.values in Formik. In your case you want to get the value of name field then you can do as follow:
<Button onClick={() => props.values.name === 'Test' ? action1 : action2}/>
or
<Button onPress={() => props.values.name === 'Test' ? action1 : action2}/>
来源:https://stackoverflow.com/questions/50456236/getfieldvalue-or-similar-in-formik