0

我想在字段有效时执行自定义函数?

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

原因是,一旦用户键入有效的邮政编码,我想让获取(GET)从 API 获取地址

4

2 回答 2

0

你可以像这样解决它:

  • Loader如果获得 URL,则具有加载数据的组件
  • 将 URL 传递给此组件,如果touched[fieldName] && !errors[fieldName]

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,它什么也不做。当 url 更改时 - 它会加载数据。

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

<Loader
  {...(touched[fieldName] && !errors[fieldName] && { url: URL_TO_FETCH })}
  onLoad={data => ...save data somewhere, etc.}
/>
于 2018-09-03T12:49:34.027 回答
0

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

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

如果要thisonValidFn方法内部访问,可以this在构造函数内部绑定或使用公共类方法

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} />
于 2018-08-31T20:23:59.803 回答