自定义变更处理程序,在Formik内部具有输入 [英] Custom change handlers with inputs inside Formik

查看:68
本文介绍了自定义变更处理程序,在Formik内部具有输入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在将使用 SUIR 制作的一些表单移植到 Formik 实现.我有一些需要自定义更改处理程序才能执行操作的输入组件.如何将我的变更处理程序传递给 onChange 道具,以便由formik跟踪值?

I'm porting some of my forms I made using SUIR over to a Formik implementation. I have input components that need custom change handlers to perform actions. How can I pass my change handler to the onChange prop so the values are tracked by formik?

我已经尝试过类似的方法,但是没有运气.

I've tried something like this, but with no luck.

onChange={e => setFieldValue(dataSchemaName, e)}

在另一篇帖子中提到的

此处.

which is mentioned in a different post here.

还提到了此处,但我不太明白让我的自定义更改处理程序与Formik完美结合.

It's also mentioned here, but I can't quite get my custom change handler to hook up nicely with Formik.

我的变更处理程序看起来像这样

My change handler looks like this

handleSchemaChange = (e, { value }) => {
  this.setState({ dataSchemaName: value }, () => {
     console.log("Chosen dataSchema ---> ", this.state.dataSchemaName);
     //also send a request the selfUri of the selected dataSchema
  });
  const schema = this.state.dataschemas.find(schema => schema.name === value);
if (schema) {
  axios
    .get(schema.selfUri)
    .then(response => {
      console.log(response);
      this.setState({
        fields: response.data.data.fields,
      });
      console.log(this.state.fields);
    })
    .catch(error => console.log(error.response));
  }
};

这是我的一个使用下拉列表的表单字段的示例

Here's an example of one of my form fields using a dropdown

<Form.Field>
  <label style={{ display: "block" }}>
    Select a Schema
  </label>
  <Dropdown
    id="dataSchemaName"
    multiple={false}
    options={dataschemas.map(schema => {
      return {
        key: schema.id,
        text: schema.name,
        value: schema.name
      };
    })}
    value={dataSchemaName}
    onChange={this.handleSchemaChange}
  />
</Form.Field>

我有一个沙盒,其中有问题

推荐答案

您可以将 setFieldValue 函数传递给函数 handleSchemaChange ,然后在内部使用它.

You can pass the setFieldValue function to your function handleSchemaChange and then use it inside.

因此,使其代替 onChange = {this.handleSchemaChange} onChange = {(e,val)=>this.handleSchemaChange(e,val,setFieldValue)} .

在您的 handleSchemaChange 函数内部:

handleSchemaChange = (e, { value }, setFieldValue) => {
    setFieldValue('dataSchemaName', value);
    ... the rest of your implementation
}

以下是已实现解决方案的沙箱: https://codesandbox.io/s/formik-create-query-schema-uq35f

Here is a sandbox with the solution implemented: https://codesandbox.io/s/formik-create-query-schema-uq35f

这篇关于自定义变更处理程序,在Formik内部具有输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆