我想以formik形式在密码字段上显示一个大写锁定指示符。我需要检测onKeyUp事件,使用formik和密码字段组件可以做到这一点(检测键盘事件)吗?
答案 0 :(得分:1)
这实际上与Formik没有任何关系。您可以像在普通输入上一样使用onKeyDown()
:
class Login extends React.PureComponent {
state = { warning: false };
/**
* Hide warning when losing focus.
* @param handleBlur Formik blur event.
* @param event Input event.
*/
onBlur(handleBlur, event) {
this.setState({ warning: false });
handleBlur(event);
}
/**
* Detect caps lock being on when typing.
* @param keyEvent On key down event.
*/
onKeyDown = keyEvent => {
if (keyEvent.getModifierState("CapsLock")) {
this.setState({ warning: true });
} else {
this.setState({ warning: false });
}
};
/**
* Show a password field that detects the caps lock key.
* @returns Form with a password field.
*/
render() {
return (
<Formik initialValues={{ password: "" }}>
<Form>
<label htmlFor="password">Password</label>
<Field name="password">
{({ field }) => (
<input
{...field}
id="password"
onBlur={this.onBlur.bind(this, field.handleBlur)}
onKeyDown={this.onKeyDown}
type="password"
/>
)}
</Field>
{this.state.warning && <div>Caps Lock On!</div>}
</Form>
</Formik>
);
}
}
看到它运作here。
这是一个最小的示例。我可能会扼制onKeyDown()
支票。