getFieldValue or similar in Formik

喜夏-厌秋 提交于 2020-04-10 07:24:11

问题


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

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