Bru*_*ceM 5 javascript reactjs formik
我正在使用 Formik (带有withFormik()),并且想要<Field>在用户输入时检查 a - 在其中包含 4 个字符之后,我想专注于下一个字段,以便他们可以继续输入而无需移动到下一个字段。
所以我的 InnerForm 有:
<Field
type="text"
name="credit1"
inputmode="numeric"
maxlength="4" />
<Field
type="text"
name="credit2"
inputmode="numeric"
maxlength="4" />
Run Code Online (Sandbox Code Playgroud)
我的FormikInnerFormContainer = withFormik(...)有一个validationSchema。
如果第一个字段有 4 个字符,我如何捕捉第一个字段的变化,并将焦点移至第二个字段?
我尝试覆盖onChange,但无法弄清楚如何使用用户输入的每个字符更新字段内容。
你可以在 Formik 中这样使用。
focusChange(e) {
if (e.target.value.length >= e.target.getAttribute("maxlength")) {
e.target.nextElementSibling.focus();
}
...
//Example implementation
import React from "react";
import { Formik } from "formik";
export default class Basic extends React.Component {
constructor(props) {
super(props);
this.inputRef = React.createRef();
this.focusChange = this.focusChange.bind(this);
}
focusChange(e) {
if (e.target.value.length >= e.target.getAttribute("maxlength")) {
e.target.nextElementSibling.focus();
}
}
render() {
return (
<div>
<h1>My Form</h1>
<Formik
initialValues={{ name: "" }}
onSubmit={(values, actions) => {
setTimeout(() => {
alert(JSON.stringify(values, null, 2));
actions.setSubmitting(false);
}, 1000);
}}
render={props => (
<form onSubmit={props.handleSubmit} ref={this.inputRef}>
<input
type="text"
onChange={props.handleChange}
onBlur={props.handleBlur}
value={props.values.name}
name="name"
maxlength="4"
onInput={e => this.focusChange(e)}
/>
<input
type="text"
onChange={props.handleChange}
onBlur={props.handleBlur}
value={props.values.lastName}
name="lastName"
maxlength="4"
onInput={this.focusChange}
/>
<button type="submit">Submit</button>
</form>
)}
/>
</div>
);
}
}Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
10286 次 |
| 最近记录: |