[英]React Formik: How to use custom onChange without manually handling state?
I want to make use of Formik's internal state handling (eg initialValues
and referencing validation via field name).我想利用 Formik 的内部状态处理(例如,
initialValues
和通过字段名称引用验证)。 However, when I try to use a custom onChange
handler, I seem to have to manually manage state for the select tag.但是,当我尝试使用自定义
onChange
处理程序时,我似乎必须手动管理 select 标记的状态。 Is there a better way to do this?有一个更好的方法吗?
state = {
selectedType: ''
};
handleForm = (val) => {
// do something else
this.setState({selectedType: val});
};
<Formik
initialValues={{
type: ''
}}
validate={
(values) => {
const errors = {};
if (!values.type) {
errors.type = "Select a value";
}
return errors;
}
}
onSubmit={
(values) => {
// getting undefined...
console.log(values.type);
}
}
>
<Form>
<Field name="type" as="select" value={this.state.selectedType} onChange={(event) => this.handleForm(event.target.value)}>
<option disabled></option>
<option value="Email">Email</option>
<option value="Text">Text</option>
<option value="Phone">Phone</option>
</Field>
<button type="submit">Submit</button>
</Form>
</Formik>
when using Formik for managing Forms , we should avoid using state to manage the Form state .使用 Formik 管理 Forms 时,应避免使用 state 来管理 Form 状态。 Formik by default provides helpers which takes care of the onChange, focus and blur events .
默认情况下,Formik 提供帮助器来处理 onChange、focus 和 blur 事件。
Field provided by Formik will handle the change events for you . Formik 提供的字段将为您处理更改事件。
<Field id="type" name="type" as="select">
<option disabled></option>
<option value="Email">Email</option>
<option value="Text">Text</option>
<option value="Phone">Phone</option>
</Field>
Hope this helps - sandbox example希望这会有所帮助 - 沙盒示例
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.