React Set a State of a component as part of a Form State

若如初见. 提交于 2020-05-17 08:49:22

问题


I have a form that that uses the wizard approach in moving between child components and finally submitting the data. I have a 3rd-party component nested in one of the child components that I use to collect user phone number using the international format.

I am unable to set the formState with the phone number provided by the 3rd-party component. I get the error TypeError: event.persist is not a function Kindly check my source code and help me set the formState with input from the phone number component.

const schema = {
     phone: {
     presence: { allowEmpty: false, message: "is required" },
     length: {
       maximum: 20,
},
}

const AboutYou = ({ formState, setFormState, navigation }) => {
  const classes = useStyles();

  const { next } = navigation;

  useEffect(() => {
  const errors = validate(formState.values, schema);

  setFormState((formState) => ({
    ...formState,
    isValid: errors ? false : true,
    errors: errors || {},
  }));
}, [formState.values, setFormState]);

const handleChange = (event) => {
  event.persist();

  setFormState((formState) => ({
    ...formState,
    values: {
    ...formState.values,
    [event.target.name]:
      event.target.type === "checkbox"
        ? event.target.checked
        : event.target.value,
  },
  touched: {
    ...formState.touched,
    [event.target.name]: true,
  },
}));
}; 

}

I use the onChange method to call the handleChange method where I try to set the phone input to the formState. Please see my codes below:

return (
  <form className={classes.form}>
     <PhoneInput
      country={"us"}
      value={formState.values.phone || ""}
      onChange={handleChange}
    />
  </form>
  );

来源:https://stackoverflow.com/questions/61839354/react-set-a-state-of-a-component-as-part-of-a-form-state

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!