多种成分可为Formik带来价值

时间:2019-02-28 19:31:00

标签: reactjs formik

我有3个<select>组件。第一部分是日子,第二部分是月份,第三部分是年份。这些组件充当一个日期选择器。我尝试用Formik的connect包装,并使用setFieldValuesetFieldError,但是在我编辑该表单中的其他组件之后,错误消失了。

我该如何解决该错误并保持不变。如我所见,这种行为是known

class DateField extends Component {
  constructor(props) {
    super(props);
    const value = props.value;
    this.state = {
      day: moment.utc(value).date(),
      month: moment.utc(value).month(),
      year: moment.utc(value).year(),
    };
  }

  handleChange = e => {
    const stateProp = e.target.name.split('.').pop();

    this.setState(
      {
        [stateProp]: e.target.value,
      },
      () => {
        const { formik } = this.props;
        const date = this.dateFromState();
        const error = this.props.validate(date);
        formik.setFieldValue(this.props.name, date, false);
        formik.setFieldError(this.props.name, error);
      }
    );
  };

  handleBlur = () => {
    const { formik } = this.props;
    const date = this.dateFromState();
    const error = this.props.validate(date);
    formik.setFieldTouched(this.props.name, true, false);
    formik.setFieldError(this.props.name, error);
  };

  dateFromState() {
    // returns date constructed from the state
  }

  render() {
    const { formik, name } = this.props;
    const error = getValueByPath(formik.errors, name);

    return (
      <div className="form-group">
        <label>{this.props.label}</label>
        <select
          name={`${this.props.name}.day`}
          value={this.state.day}
          onChange={this.handleChange}
          onBlur={this.handleBlur}
        >
          {
            // options for days
          }
        </select>
        <select
          name={`${this.props.name}.month`}
          value={this.state.month}
          onChange={this.handleChange}
          onBlur={this.handleBlur}
        >
          {
            // options for months
          }
        </select>
        <select
          name={`${this.props.name}.year`}
          value={this.state.year}
          onChange={this.handleChange}
          onBlur={this.handleBlur}
        >
          {
            // options for years
          }
        </select>
        {error && (
          <div className="validation-message">
            <span>{error}</span>
          </div>
        )}
      </div>
    );
  }
}

const getValueByPath = (obj, path) => path.split('.').reduce((o, i) => o && o[i], obj);

export default connect(DateField);

1 个答案:

答案 0 :(得分:1)

我的建议是将组件与Formik分离,让它提供日期并相应地处理更改。然后,您可以使用该表单确定提供的日期是否有效,并将错误传递给受控组件以显示直到该日期有效为止。这对于重用性也很棒。

const DatePicker = ({ name, value, error, onChange, onBlur }) => {
  const today = new Date(value);  
  const [day, setDay] = useState(today.getUTCDay());
  const [month, setMonth] = useState(today.getUTCMonth());
  const [year, setYear] = useState(today.getUTCYear());

  useEffect() => {
   const newDate = new Date([year, month, day]);
   const target = { name, value: newDate };

   onChange({ target });
  }, [day, month, year]);

  return (
    //do your JSX here;
  );
}