【发布时间】:2022-01-04 23:35:32
【问题描述】:
我在一个表单中有 3 个字段:fieldA fieldB fieldC。
我想要什么:我希望用户尚未填写的第三个字段成为其他两个字段的函数。例如。如果将字段fieldA 和fieldB 分别设置为1 和2,我希望fieldC 为1/2。如何让这个动态的、依赖的字段工作?
我目前正在使用 FormIK 包,但会接受任何答案。
这是我当前的构建:
const MyFieldC = (props) => {
const {
values: { textA, textB },
touched,
setFieldValue,
} = useFormikContext();
const [field, meta] = useField(props);
React.useEffect(() => {
// set the value of textC, based on textA and textB
if (
textA.trim() !== '' &&
textB.trim() !== '' &&
touched.textA &&
touched.textB
) {
setFieldValue(props.name, textA/textB);
}
}, [textB, textA, touched.textA, touched.textB, setFieldValue, props.name]);
return (
<>
<input {...props} {...field} />
{!!meta.touched && !!meta.error && <div>{meta.error}</div>}
</>
);
};
const MyFieldA = (props) => {
const {
values: { textC, textB },
touched,
setFieldValue,
} = useFormikContext();
const [field, meta] = useField(props);
React.useEffect(() => {
// set the value of textC, based on textA and textB
if (
textC.trim() !== '' &&
textB.trim() !== '' &&
touched.textA &&
touched.textB
) {
setFieldValue(props.name, textA/textB);
}
}, [textB, textC, touched.textA, touched.textB, setFieldValue, props.name]);
return (
<>
<input {...props} {...field} />
{!!meta.touched && !!meta.error && <div>{meta.error}</div>}
</>
);
};
const MyFieldB = (props) => {
const {
values: { textA, textC },
touched,
setFieldValue,
} = useFormikContext();
const [field, meta] = useField(props);
React.useEffect(() => {
// set the value of textC, based on textA and textB
if (
textA.trim() !== '' &&
textC.trim() !== '' &&
touched.textA &&
touched.textC
) {
setFieldValue(props.name, textA/textC);
}
}, [textC, textA, touched.textA, touched.textC, setFieldValue, props.name]);
return (
<>
<input {...props} {...field} />
{!!meta.touched && !!meta.error && <div>{meta.error}</div>}
</>
);
};
function Form() {
// Note that we provide initalValues all 3 fields.
const initialValues = { textA: '', textB: '', textC: '' };
return (
<div className="App">
<Formik
initialValues={initialValues}
onSubmit={async (values) => alert(JSON.stringify(values, null, 2))}
>
<div className="section">
<Form>
<label>
FieldA
<MyFieldA name="textA" />
</label>
<label>
FieldB
<MyFieldB name="textB" />
</label>
<label>
FieldC
<MyFieldC name="textC" />
</label>
<button type="submit">Submit</button>
</Form>
</div>
</Formik>
</div>
);
}
如果我为 3 个值中的 2 个提交值,我会收到错误:
TypeError: textB.trim 不是函数
【问题讨论】:
-
我在想,
MyFieldC是如何获取values: { textA, textB }中textA和textB的值的。
标签: javascript reactjs formik