单个输入上的多个字段名称
Multiple field names on single input
我是 React 和 Formik 的新手。我有一个关于如何在位置对象中同时获取 lat 和 lang 的问题。我在输入位置得到 [object, Object ]。为了证明我的问题。我创建了一个沙箱 https://codesandbox.io/embed/great-payne-hk6nd。谢谢!
您可以将 MyEnhancedForm 更改为:
mapPropsToValues({ location }) {
return {location:[location.lat,location.lng]}
}
或类似的东西。这样你就可以渲染 lng 和 lat
在MyForm
中,你将获得values
个道具。
const { values, touched, errors, isSubmitting } = props;
let location = values.location;
location = `lat:${location.lat}, lng:${location.lng}`
在Field
中你需要设置value
prop,
<Field value={location} name="location" type="text" className="c-input" readOnly />
这是你的沙盒修复程序
基本上,我将你的 mapPropsToValues
更改为:
mapPropsToValues({ location }) {
const lat = location.lat || "";
const lng = location.lng || "";
return {
location: `${lat}, ${lng}`,
};
},
const MyForm = props => {
const { touched, errors, isSubmitting, values } = props; // Formik pass values to props
return (
<Form>
<input type="text" value={`${values.location.lat}, ${values.location.lng}`} readOnly/> // We preferred input instead of Field.
{touched.location && errors.location && (
<p className="u-text-red-600 text-xs mt-2 absolute u-mt-4">
{errors.location}
</p>
)}
<button
type="submit"
className="c-button c-button--info c-button--block u-my-4"
disabled={isSubmitting}
>
Submit
</button>
<DisplayFormikState {...props} />
</Form>
);
};
我是 React 和 Formik 的新手。我有一个关于如何在位置对象中同时获取 lat 和 lang 的问题。我在输入位置得到 [object, Object ]。为了证明我的问题。我创建了一个沙箱 https://codesandbox.io/embed/great-payne-hk6nd。谢谢!
您可以将 MyEnhancedForm 更改为:
mapPropsToValues({ location }) {
return {location:[location.lat,location.lng]}
}
或类似的东西。这样你就可以渲染 lng 和 lat
在MyForm
中,你将获得values
个道具。
const { values, touched, errors, isSubmitting } = props;
let location = values.location;
location = `lat:${location.lat}, lng:${location.lng}`
在Field
中你需要设置value
prop,
<Field value={location} name="location" type="text" className="c-input" readOnly />
这是你的沙盒修复程序
基本上,我将你的 mapPropsToValues
更改为:
mapPropsToValues({ location }) {
const lat = location.lat || "";
const lng = location.lng || "";
return {
location: `${lat}, ${lng}`,
};
},
const MyForm = props => {
const { touched, errors, isSubmitting, values } = props; // Formik pass values to props
return (
<Form>
<input type="text" value={`${values.location.lat}, ${values.location.lng}`} readOnly/> // We preferred input instead of Field.
{touched.location && errors.location && (
<p className="u-text-red-600 text-xs mt-2 absolute u-mt-4">
{errors.location}
</p>
)}
<button
type="submit"
className="c-button c-button--info c-button--block u-my-4"
disabled={isSubmitting}
>
Submit
</button>
<DisplayFormikState {...props} />
</Form>
);
};