使用 formik 重置 React-boostrap-typeahead

Tra*_*Rob 5 reactjs react-bootstrap-typeahead formik

我正在使用react-boostrap-typeahead 库中的AsyncTypeahead 和Formik。两个很棒的小图书馆。我的代码的简化版本如下所示

const SearchFilter = withFormik({ 
  mapPropsToValues: (props) {
    office: someIncomingValue || [{name: 'office1', id: 1}]
  }
})(TheForm)

const TheForm = (props) => {
  const {values, handleReset} = props;
  return (
    <form>
     <AsyncTypeahead 
       defaultSelected={[values.office]}  
       options={...} 
       onChange={...SetNewValue...}
       onSearch={...}/>

      <button onClick={handleReset}
    </form>
  )
}
Run Code Online (Sandbox Code Playgroud)

通过使用 AsynchTypeahead 上的 defaultSelected 属性。我可以设置默认的初始值。但我遇到的问题是,当我单击handleRest按钮时,formik会执行其操作并将值重置回office 1,但AsynchTypeahead没有办法手动将值传递回其中。所以它不会改变。我看到有一个selected可用的道具,但当我尝试使用它时它就会爆炸。任何输入都会很大

更新:

是的,选定的是我需要的。我必须添加一个 onInputChange 属性以使父级与正在键入的内容保持同步。

Leo*_*hko 4

我也有同样的问题。
我想出了这个解决方案:

import { Formik } from "formik";
import * as Yup from "yup";
import { Typeahead } from 'react-bootstrap-typeahead';

const AddCheckSchema = Yup.object().shape({
  title: Yup.string()
      .min(2, 'Too Short!')
      .max(50, 'Too Long!')
      .required('Required')
});

...

render() {
  const users = [
    { id: 1, fullname: 'User #1' },
    { id: 2, fullname: 'User #2' },
    { id: 3, fullname: 'User #3' },
  ];

  return (
    <Formik
        initialValues={{
          title: '',
          amount: 0,
          actualDate: new Date()
        }}
        validationSchema={AddCheckSchema}
        onSubmit={ this.onSubmit}
    >
      {({
          errors,
          touched,
          handleChange,
          handleBlur,
          handleSubmit,
          setFieldValue,
          setFieldTouched,
      }) => (
          <form onSubmit={handleSubmit}>
            <div className="form-group required">
              <label className="control-label">Title:</label>              

              <Typeahead
                  multiple={false}
                  onChange={(selected) => {
                    const value = (selected.length > 0) ? selected[0].fullname : '';
                    setFieldValue('title', value);
                  }}
                  onInputChange={(text, event) => setFieldValue('title', text)}}
                  onBlur={(e) => setFieldTouched('title', true)}
                  labelKey="fullname"
                  options={users}
              />
              <div className="text-danger">{touched.title && errors.title}</div>
            </div>

            <div className="form-group">
              <button type="submit" className="btn btn-primary btn-lg">Add check</button>
            </div>
          </form>
      )}
    </Formik>
  )
}
Run Code Online (Sandbox Code Playgroud)

当然,您可以将这个复杂的逻辑(围绕 Typeahead 字段)提取到单独的组件中。

参考API。