如何在Formick中使用REACTION數字格式 [英] how to use react number format with formik
本文介紹了如何在Formick中使用REACTION數字格式的處理方法,對大家解決問題具有一定的參考價值,需要的朋友們下面隨著小編來一起學習吧!
問題描述
我的表格如下
const NewProduct = ({}) => {
const validate = (values) => {
const errors = {}
if (!values.title) {
errors.title = 'Required'
}
return errors
}
const formik = useFormik({
initialValues: {
title: '',
price: '',
},
validate,
onSubmit: (values) => {
alert(JSON.stringify(values, null, 2))
},
})
return (
<div className="newProductComponent">
<form onSubmit={formik.handleSubmit}>
<label>title</label>
<input
type="text"
id="title"
name="title"
onChange={formik.handleChange}
value={formik.values.title}
/>
{formik.errors.title ? (
<div className="error">{formik.errors.title}</div>
) : null}
<NumberFormat
value={formik.values.price}
thousandSeparator={true}
onValueChange={(values) => {
const { formattedValue, value } = values
}}
/>
</form>
</div>
)
}
如何使表單中數字格式組件與Formik一起使用?
推薦答案
useFormik
-您已經使用的掛鉤-返回可用于手動設置值的函數setFieldValue
。
price
,第二個是值。您還必須在<NumberFormat>
上設置屬性name="price"
。
const App = () => {
const validate = (values) => {
const errors = {}
if (!values.title) {
errors.title = 'Required'
}
return errors
}
const formik = useFormik({
initialValues: {
title: '',
price: '',
},
validate,
onSubmit: (values) => {
alert(JSON.stringify(values, null, 2))
},
})
return (
<div className="newProductComponent">
<form onSubmit={formik.handleSubmit}>
<label>title</label>
<input
type="text"
id="title"
name="title"
onChange={formik.handleChange}
value={formik.values.title}
/>
{formik.errors.title ? (
<div className="error">{formik.errors.title}</div>
) : null}
<br />
<label>Price</label>
<NumberFormat
name="price"
value={formik.values.price}
thousandSeparator={true}
onValueChange={(values) => {
const { value } = values;
formik.setFieldValue('price', value);
}}
/>
<br />
<button type="submit">Submit</button>
</form>
</div>
)
};
這篇關于如何在Formick中使用REACTION數字格式的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持IT屋!
查看全文