在我的react项目中,我正在使用Formik库。对于输入,我正在使用TextInputMask,这是其他库。
export default function Calc() {
return (
<Formik
initialValues={{ monthly_rental: '', }}
>
{(props) => (
<View>
<Text>Monthly rental</Text>
<TextInputMask
type={"money"}
options={{
precision: 0,
separator: ".",
delimiter: ",",
unit: "£",
suffixUnit: ""
}}
placeholder={"£500"}
value={props.values.monthly_rental}
includeRawValueInChangeText={true}
onChangeText={props.handleChange('monthly_rental')}
/>
</View>
)}
</Formik>
)
}
上面的代码很好用,但是我想要的是在onChangeText={props.handleChange('monthly_rental')}
上设置原始值而不是格式化值。
我已经看到了这段代码,但是我现在不打算执行此代码
onChangeText={(text, rawValue) => {
this.setState({
value: text,
raw: rawValue
})
所以最后我找到了。 Formik库中有一个称为setFieldValue: (field: string, value: any, shouldValidate?: boolean) => void
的函数。 see here
所以我的最终解决方案是:
<TextInputMask
type={"money"}
options={{
precision: 0,
separator: ".",
delimiter: ",",
unit: "£",
suffixUnit: ""
}}
style={globalstyles.input}
textAlign={"center"}
placeholder={"£500"}
keyboardType={"decimal-pad"}
value={props.values.monthly_rental}
includeRawValueInChangeText={true}
onChangeText={(maskedText, rawText) => {
// Set RawText
props.setFieldValue('monthly_rental', rawText)
}}
/>