我想使用Cleave (有关详细信息,请参阅https://nosir.github.io/cleave.js/ )作为Formik表单中的Field。虽然像文本输入这样的内置组件工作得很好,但Cleave值的更改不会被记录下来,而且如果表单中的任何其他值发生更改,它都会被重置。
也许这是一个很好的解释,为什么这是一个坏主意。下面的设置不能开箱即用,这让我很困惑。我希望值不会被重置,并存储在表单的values中,最终提交。
我使用了以下代码:
import React from "react";
import { Formik, Form, Field, ErrorMessage } from "formik";
import Cleave from 'cleave.js/react';
class App extends React.Component {
render() {
return <div>
<Formik
initialValues={{ title: "", price: 0 }}
validate={values => {
this.setState({ validationErrorDetails: null, errorMessage: "" });
let errors = {title: "", price: ""};
console.log("validate values", values);
if (!values.price || isNaN(values.price)) {
errors.price = "Price amount is required";
}
return errors;
}}
onSubmit={values => {
alert(JSON.stringify(values));
}}
render={({ isSubmitting, handleSubmit, handleChange, handleBlur, values }) => (
<Form>
<table>
<tbody>
<tr>
<td>
<label>Title:</label>
</td>
<td>
<Field name="title" component="input" />
</td>
<td>
<ErrorMessage name="title" component="div" />
</td>
</tr>
<tr>
<td>
<label>Price:</label>
</td>
<td>
<Field name="price" component={() => <Cleave value={values.price}
options={{numericOnly: true, numeral: true, numeralThousandsGroupStyle: "thousand"}} />}/>
</td>
<td>
<ErrorMessage name="price" component="div" />
</td>
</tr>
</tbody>
</table>
<button type="submit" disabled={isSubmitting} className="confirm-button">
Submit
</button>
</Form>
)}/>
</div>;
}
}
export default App;在首页上只有ReactDOM.render(<App />, document.getElementById('root'))。https://gitlab.com/krichter/react-formik-with-cleave提供了一个SSCCE,提供了样板,但没有提供更多的逻辑。
发布于 2019-07-01 04:48:06
Formik不会像<Field>那样神奇地将handleChange绑定到<Cleave>元素。你需要像这样自己绑定它:
<Cleave value={values.price}
options={...}
onChange={handleChange}
/>Cleave onChange事件同时具有显示值和原始值(例如{value: $1,000, rawvalue: 1000})。
我假设对于大多数实现,您都希望将原始值传递给Formik,因此您需要向<Cleave>组件添加一个自定义事件。
<Cleave value={values.price}
options={...}
onChange={event => {
const tempEvent = event
tempEvent.target.value = event.target.rawValue
handleChange(tempEvent)
}}
/>https://stackoverflow.com/questions/56827911
复制相似问题