【问题标题】:(P)react trigger method in functional ChildComponent(P)函数式子组件中的react触发方法
【发布时间】:2020-05-30 04:05:46
【问题描述】:

我正在 Preact 中构建一个表单,并且努力验证表单提交上的输入。

<TextInput> 组件从validate.js 获取验证对象并自行处理验证。

父组件是以formData 状态存储数据并将值提交给API 的表单。

在提交之前,我想再次验证数据以防止用户跳过一些必需的输入。

问题:解决这个问题的“反应方式”是什么?

输入:

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 
  );
}

表格:

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>
  );
}

【问题讨论】:

标签: javascript reactjs components preact


【解决方案1】:

试试下面。希望对你有帮助

  //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>
     );
  }

【讨论】:

    猜你喜欢
    • 2017-05-20
    • 2020-12-29
    • 1970-01-01
    • 1970-01-01
    • 2018-10-27
    • 2021-02-05
    • 2019-02-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多