简体   繁体   中英

(P)react trigger method in functional ChildComponent

i'm building a form in Preact and struggle to validate the inputs on form submit.

The <TextInput> Component gets passed a validation object from validate.js and handle the validation on it's own.

The parent Component is a form that stores the data in a formData state and submits the values to an API.

Before submitting i want to validate the data again to prevent the user skipping some required inputs.

Question: What's the "react-way" to solve this problem?

Input:

export default function TextInput({ onChange, validation }) {
  const [value, setValue] = useState(null);
  const [error, setError] = useState(null);

  useEffect(() => {
    onChange && onChange(value);
  }, [value]);

  const handleBlur = (e) => {
    const value = e.currentTarget.value;

    if (validation) {
      const errors = validate.single(value, validation);

      if (errors) {
        setError(errors[0]);
      }
    }
  };

  return (
    <input
      type="text"
      onBlur={handleBlur}
      onInput={e => setValue(e.target.value)}
      onFocus={() => setError(null)}
    />
    // show some error msg. if error is set 
  );
}

Form:

export default function CompetitionForm() {
  const [formData, setFormData] = useState({});

  const submitForm = async (e) => {
    e.preventDefault();
    // validate data, submit the form
  };

  const competitionTextInput = (key) => {
    return (
      <TextInput
        name={key}
        validation={RULES[key]}
        onChange={value => {
          formData[key] = value;
          setFormData(formData);
        }}
      />
    );
  };

  return (
    <form className="c-form" onSubmit={submitForm}>
      <div className="row mb-4">
        <div className="col-12 col-md-6">
          {competitionTextInput('firstName')}
        </div>
        <div className="col-12 col-md-6">
          {competitionTextInput('lastName')}
        </div>
      </div>
    </form>
  );
}

try below . hope it will help

  //Form:

  const submitForm = async (e) => {
    e.preventDefault();
    e.stopPropagation();
    // validate data, submit the form
  };

  render() {
    const { validated } = this.state;
    ......
   return (
    <Form noValidate validated={validated} onSubmit={submitForm}>
    </form>
     );
  }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM