一旦字段在Formikl / Yup中有效,如何执行自定义功能

时间:2018-08-31 20:08:43

标签: reactjs formik yup

我想在字段变为有效时执行自定义功能吗?

类似这样的东西..
<Field name="postal-code" onValid={...} />

原因是我希望用户输入有效的邮政编码后,通过API来获取地址(GET)

2 个答案:

答案 0 :(得分:0)

您可以在组件类内部或组件外部定义自定义函数。

// outside the component (best suited for functional component)
const onValidFn = () => {
 // perform action
}
// inside the component (best suited for stateful component)
onValidFn() {
 // perform action
}

如果要在this方法内访问onValidFn,则可以在构造函数内绑定this或使用public class method

onValidFn = () => {
  // perform action
  console.log(this)
}

// if your method is defined in outer scope
<Field name="postal-code" onValid={onValidFn} />

// if your method is defined in inner scope (inside class)
<Field name="postal-code" onValid={this.onValidFn} />

答案 1 :(得分:0)

您可以这样解决:

  • 具有Loader组件,该组件会在获取URL时加载数据
  • 如果touched[fieldName] && !errors[fieldName],则将URL传递给该组件

Loader组件可以像

import { PureComponent } from 'react';
import PropTypes from 'prop-types';
import superagent from 'superagent'; // swap to your xhr library of choice

class Loader extends PureComponent {
  static propTypes = {
    url: PropTypes.string,
    onLoad: PropTypes.func,
    onError: PropTypes.func
  }

  static defaultProps = {
    url: '',
    onLoad: _ => {},
    onError: err => console.log(err)
  }

  state = {
    loading: false,
    data: null
  }

  componentDidMount() {
    this._isMounted = true;
    if (this.props.url) {
      this.getData()
    }
  }

  componentWillReceiveProps(nextProps) {
    if (nextProps.url !== this.props.url) {
      this.getData(nextProps)
    }
  }

  componentWillUnmount() {
    this._isMounted = false
  }

  getData = (props = this.props) => {
    const { url, onLoad, onError } = props;

    if (!url) {
      return
    }

    this.setState({ data: null, loading: true });

    const request = this.currentRequest = superagent.
      get(url).
      then(({ body: data }) => {
        if (this._isMounted && request === this.currentRequest) {
          this.setState({ data, loading: false }, _ => onLoad({ data }));
        }
      }).
      catch(err => {
        if (this._isMounted && request === this.currentRequest) {
          this.setState({ loading: false });
        }
        onError(err);
      });
  }

  render() {
    const { children } = this.props;
    return children instanceof Function ?
      children(this.state) :
      children || null;
  }
}

如果未传递url,则不执行任何操作。网址更改时-会加载数据。

Formik渲染/儿童道具中的用法:

<Loader
  {...(touched[fieldName] && !errors[fieldName] && { url: URL_TO_FETCH })}
  onLoad={data => ...save data somewhere, etc.}
/>