【问题标题】:reactjs - Cannot read properties of undefined (reading 'type') formik with custom componentreactjs - 无法使用自定义组件读取未定义(读取 \'type\')formik 的属性
【发布时间】:2022-08-10 16:13:10
【问题描述】:

我将 formik 与我的自定义组件一起使用。

这就是我使用的方式

<Field id=\"basic-typeahead-single\"
    options={this.state.variables}
    labelKey=\"name\"
    selected={this.state.singleSelection}
    placeholder=\"Choose a Variable\" name={`conditions.${index}.variable`}
    component={AutoComplete} />

这是我的AutoComplete 使用Typehead

const AutoComplete = ({ field, form, ...props }) => {
  return <Typeahead
    {...field} {...props}
  />
};

这会呈现下拉菜单并选择它显示的任何值

Formik.tsx:600 Uncaught TypeError: Cannot read properties of undefined (reading \'type\')
    at Formik.tsx:600:1
    at Formik.tsx:653:1
    at Object.onChange (Formik.tsx:1200:1)
    at Typeahead._handleChange (Typeahead.js:358:1)
    at Typeahead.<anonymous> (Typeahead.js:530:1)
    at callCallback (react-dom.development.js:12318:1)
    at commitUpdateQueue (react-dom.development.js:12339:1)

可能是什么问题?我该如何解决这个问题?

    标签: reactjs formik


    【解决方案1】:

    我必须添加onChange 方法,然后使用setFieldValue 需要像这样更新值

    onChange={e => {
               if (e && e.length) {
                 setFieldValue(`conditions.${index}.variable`, e[0].name)
               } else {
                 setFieldValue(`conditions.${index}.variable`, null);
               }
             }}
    

    【讨论】:

      猜你喜欢
      • 2022-08-18
      • 1970-01-01
      • 2021-12-06
      • 2021-12-06
      • 2022-07-22
      • 2021-11-24
      • 2016-08-08
      • 2018-12-16
      • 1970-01-01
      相关资源
      最近更新 更多