如何在打字稿地图中正确使用 formik.values?

How to properly use formik.values in map for typescript?

我在使用 useFormik 打字稿时遇到错误,有人可以帮忙吗?非常感谢。

在行 const value = formik.values[field.name]; 中,我收到此错误: 元素隐式具有 'any' 类型,因为 'string' 类型的表达式不能用于索引类型 '{ name: string;描述:字符串;颜色:字符串; }'.

const fields = [
  {name: 'name', label: 'GENERAL.NAME'},
  {name: 'description', label: 'GENERAL.DESC'},
  {name: 'color', label: 'GENERAL.COLOR'}
];

export const Create: React.FC = () => {
  const {loading} = useSelector<RootState>(
    (state) => state.calendarReducer,
    shallowEqual
  ) as CalendarState;

  const formik = useFormik({
    enableReinitialize: true,
    initialValues: {name: '', description: '', color: Constants.COLORS.AppleRed},
    onSubmit: (values) => {
      console.log(values);
    }
  });

  return (
    <form className='form' onSubmit={formik.handleSubmit}>
      {fields.map((field, index) => {
        const value = formik.values[field.name];
        return (
          <div
            key={index}
            className='sm-6 md-4 lg-3 my-3 d-flex justify-content-between align-items-center'
          >
            <label className=''>
              <FormattedMessage id={field.label} />
            </label>
            <TextField
              disabled={loading}
              fullWidth={false}
              name={field.name}
              onChange={formik.handleChange}
              value={'xxxxxx'}
              variant='standard'
            />
          </div>
        );
      })}
    </form>
  );
};

the code here

您可以使用 const 断言将 fields 指定为文字值。

type Values = {
  name: string;
  description: string;
  color: string;
}
declare const values: Values;

const fields = [
  {name: 'name', label: 'GENERAL.NAME'},
  {name: 'description', label: 'GENERAL.DESC'},
  {name: 'color', label: 'GENERAL.COLOR'}
] as const;

fields.map((field) => values[field.name]); // no error