0

我正在使用一个名为 Kendo React 的 React 库来创建一个简单的表单。我想要的是能够通过单击“加载新用户”按钮更改数据时提交我的表单,但是当前的行为是,当我单击该按钮并填充数据时,提交按钮不会提交表单,直到我手动更改字段的值,为什么以及如何在更新数据并启用按钮后立即提交表单?这是我的代码:

import React from 'react';
import ReactDOM from 'react-dom';
import { Form, Field, FormElement } from '@progress/kendo-react-form';
import { Error } from '@progress/kendo-react-labels';
import { Input } from '@progress/kendo-react-inputs';
const emailRegex = new RegExp(/\S+@\S+\.\S+/);

const emailValidator = value => emailRegex.test(value) ? "" : "Please enter a valid email.";

const EmailInput = fieldRenderProps => {
  const {
    validationMessage,
    visited,
    ...others
  } = fieldRenderProps;
  return <div>
        <Input {...others} />
        {visited && validationMessage && <Error>{validationMessage}</Error>}
      </div>;
};

const App = () => {
  const handleSubmit = dataItem => alert(JSON.stringify(dataItem, null, 2));

  const [user, setUser] = React.useState({
    firstName: 'John',
    lastName: 'Smith',
    email: 'John.Smith@email.com'
  });

  const loadNewUser = () => {
    setUser({
      firstName: 'NewFirstName',
      lastName: 'NewLastName',
      email: 'NewEmails@email.com'
    });
  };

  return <React.Fragment>
        <button className='k-button' onClick={loadNewUser}> Load new user </button>
        <hr className='k-hr' />
        <Form onSubmit={handleSubmit} initialValues={user} key={JSON.stringify(user)} render={formRenderProps => <FormElement style={{
      maxWidth: 650
    }}>
              <fieldset className={'k-form-fieldset'}>
                <legend className={'k-form-legend'}>Please fill in the fields:</legend>
                <div className="mb-3">
                  <Field name={'firstName'} component={Input} label={'First name'} />
                </div>

                <div className="mb-3">
                  <Field name={'lastName'} component={Input} label={'Last name'} />
                </div>

                <div className="mb-3">
                  <Field name={"email"} type={"email"} component={EmailInput} label={"Email"} validator={emailValidator} />
                </div>
              </fieldset>
              <div className="k-form-buttons">
                <button type={'submit'} className="k-button" disabled={!formRenderProps.allowSubmit}>
                  Submit
                </button>
              </div>
            </FormElement>} />
      </React.Fragment>;
};

ReactDOM.render(<App />, document.querySelector('my-app'));
4

1 回答 1

0

这是正常的,因为当您使用setUser渲染事件而不是输入上的更改事件时,因此要在每次loadNewUser 单击时提交表单,您可以将提交逻辑添加到loadNewUser方法 after setUsersetUser最后一个选项更好,因为您避免在调用 inside之前触发提交逻辑 loadNewUser

或者使用 UseEffect 对用户对象的每次更改执行提交。

  useEffect(() => {
      console.log(user);
  }, [user]);

这是一个简单的例子(没有剑道):

import { useEffect, useState } from "react";

export default function App() {
  const [user, setUser] = useState(null);

  const loadNewUser = () => {
    setUser({ name: "alan" });
  };
  const onchange = (event) => {
    setUser({
      ...user,
      name: event.target.value
    });
  };
  const submit = () => {
    console.log("submit", user);
  };
  useEffect(() => {
    user && submit();
  }, [user]);

  return (
    <div className="App">
      <button onClick={loadNewUser}>Load new user</button>
      <input
        type="text"
        onChange={onchange}
        value={user != null ? user.name : ""}
      />
      <button onClick={submit}>submit</button>
    </div>
  );
}
于 2021-10-20T09:39:56.647 回答