[英]How to add a Clear Button on a Formik Textfield
我想添加一個清除按鈕以方便用戶:
constructor(props) {
this.emailInput = React.createRef();
}
<Field label="Email" name="email" ref={this.emailInput} onChange={onChange} component={TextField}/>
但是得到這個:
Warning: Function components cannot be given refs. Attempts to access this ref will fail.
要重置特定字段,請使用setFieldValue
將值設置為空字符串。
setFieldValue: (field: string, value: any, shouldValidate?: boolean) => void
強制設置字段的值。
field
應與您希望更新的values
的鍵匹配。 用於創建自定義輸入更改處理程序。
例如:
<Formik
initialValues={initialValues}
...
>
{({ setFieldValue }) =>
...
<button type="reset" onClick={() => setFieldValue('fieldName', '')}>
Reset This
</button>
...
要重置所有字段,請使用resetForm
。
resetForm: (nextValues?: Values) => void
當務之急是重置表格。 這將清除
errors
和touched
,設置isSubmitting
到false
,isValidating
到false
,然后重新運行mapPropsToValues
當前WrappedComponent的道具或什么作為參數傳遞。
例如:
<Formik
initialValues={initialValues}
...
>
{({ resetForm }) =>
...
<button type="reset" onClick={resetForm}>
Reset All
</button>
...
代碼沙盒: https ://codesandbox.io/s/7122xmovnq
Formik 有一個名為resetForm的內置方法,可以像其他 formik 方法一樣訪問它。 在你的形式中,你可能有類似的東西
<Formik
initialValues={something}
validationSchem={someSchema}
render={() => {
...some form stuff
}
}
/>
您可以訪問該渲染方法中的 formik 道具並使用它們執行您想要的操作:
<Formik
initialValues={something}
validationSchem={someSchema}
render={(props) => {
...some form stuff
<button type="button" onClick={() => props.resetForm()}>reset form</button>
}
}
/>
您可以嘗試在表單中設置重置按鈕,例如
<form>
<Field label="Email" name="email" onChange={onChange} component={TextField}/>
<input type="reset" value="Reset">
</form>
我以這里為例,它必須重置表單中的所有輸入
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.