【问题标题】:In react-redux-form, how to disable submit button until all required field are not filled up在 react-redux-form 中,如何禁用提交按钮,直到未填写所有必填字段
【发布时间】:2017-11-21 12:25:07
【问题描述】:

在 React 应用程序 from this tutorial 上工作,我需要一个处理表单和验证的库,并且以下 2 个库出现在最多的搜索结果中

  1. redux-form
  2. react-redux-form

首先,不知道需要使用哪个,所以按照以下步骤尝试了后者

请查看demo here

1) 在 reducers.js

中使用combineReducers 中的createForms()
const initialUserState = {
  firstName: '',
  lastName: '',
  userName: '',
  email: '',
  password: '',
  confirmPassword: ''
};

const rootReducer = combineReducers({
    ...createForms({
        user: initialUserState
    })
});

2) 在 RegisterPage.js 我已经使用和 Component 来创建表单

class RegisterPage extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      user: {
        firstName: '',
        lastName: '',
        username: '',
        email: '',
        password: '',
        confirmPassword: ''
      },
      submitted: false
    };

    this.handleChange = this.handleChange.bind(this);
    this.handleSubmit = this.handleSubmit.bind(this);
  }

  handleChange(event) {
    const { name, value } = event.target;
    console.log(`handleChange called => name ${name}, value: ${value}`);
    const { user } = this.state;
    this.setState({
      user: {
        ...user,
        [name]: value
      }
    });
  }

  handleSubmit(user) {
    console.log("handleSubmit state", this.state);
    this.setState({ submitted: true });
    const { user } = this.state;
    console.log("user", user);
    const { dispatch } = this.props;
    dispatch(userActions.register(user));
  }

  render() {
    return (
      <div className="col-md-6 col-md-offset-3">
        <h2>Register</h2>
        <Form model="user" onSubmit={(user) => this.handleSubmit(user)} >
          <div className="form-group">
            <label htmlFor="firstName">First Name</label>
            <Control.text
              id="firstName"
              className="form-control"
              model=".firstName"
              onChange={this.handleChange}
              validators={{ required: isRequired, maxLength: maxLength(50) }}
              validateOn="blur"
            />
            <Errors
              model=".firstName"
              className="errors text-danger"
              show="touched"
              messages={{
                required: 'Please provide First Name.',
                maxLength: 'Maximum length can be 50 characters.'
              }}
            />
          </div>
          <div className="form-group">
            <label htmlFor="lastName">Last Name</label>
            <Control.text className="form-control" model=".lastName" onChange={this.handleChange} />
          </div>
          <div className="form-group">
            <label htmlFor="username">Username</label>
            <Control.text className="form-control" model=".username" onChange={this.handleChange} />
          </div>
          <div className="form-group">
            <label htmlFor="firstName">Email Address</label>
            <Control.text className="form-control" model=".email" onChange={this.handleChange} />
          </div>
          <div className="form-group">
            <label htmlFor="password">Password</label>
            <Control type="password" className="form-control" model=".password" onChange={this.handleChange} />
          </div>
          <div className="form-group">
            <label htmlFor="confirmPassword">Confirm Password</label>
            <Control type="password" id="confirmPassword" className="form-control" model=".confirmPassword" onChange={this.handleChange} />
          </div>
          <div className="form-group">
            <button type="submit" className="btn btn-primary" >Register</button>
          </div>
        </Form>
      </div>
    );
  }
}

const connectedRegisterPage = connect()(RegisterPage);
export { connectedRegisterPage as RegisterPage };

当我点击提交按钮时,状态变为 "USER_REGISTER_REQUEST" 状态,但它在用户数据中添加了附加属性,如下所示

user: {
confirmPassword : ""
email: ""
firstName: ""
lastName: ""
password: ""
user.firstName: "foo" << added extra property
username: ""

所以我的集体疑问是(请允许我在一篇帖子中提出类似的问题,请您不要投反对票,它们都是密切相关的)

  1. 当我们已经在combineReducer 中定义为initialUserState 时,为什么还要在RegisterPage constructor() 中再次定义this.state = { user : {} }。 我不完全理解这一点,请帮助我。

  2. 如何在所有必填字段未填满之前禁用提交按钮?从角度背景调用,我们使用ng-pristineng-touchedng-valid 和许多其他指令来检查表单字段并在ng-disabled 中写入表达式以禁用提交按钮。

那么类似的功能可以在 react 中实现吗?

  1. 还在控制台中检查了每次不必要地调用焦点/模糊状态(type: "rrf/focus")。如何防止它们或者这是正常的反应行为并且一般不会影响我们的页面?

  2. 为什么在提交时会在用户对象中添加额外的数据?

  3. 从上面哪个库对用户更友好?

【问题讨论】:

    标签: reactjs react-redux-form


    【解决方案1】:

    首先我使用 redux.. 最简单的方法是设置您的 disable = {invalid}。

    &lt;Button type="submit" disabled={invalid}&gt;Submit&lt;/Button&gt;

    如果你console.log(props);在道具中

    您会发现许多键,例如无效、有效、原始、提交、提交。

    它们中的大多数都具有布尔值 true 和 false,并且随着您在表单上执行操作而变化。

    当我的表单无效(invalid)无效时为真。

    但是当字段被填充时,无效变量将为 false。

    在这里你可以使用它。

    const SyncValidationForm = (props) => { const {handleSubmit, pristine, reset, submitting, invalid} = props; console.log(props);

    设置无效的道具来使用它。

    然后添加 disable = {invalid}

    但我有一个更好的简单解决方案: 做这样的事情:

    disabled="{!this.state.user.lastName || !this.state.username.email || !this.state.user.password}

    这将一直返回 true,直到所有字段都被填满

    【讨论】:

      【解决方案2】:

      最好的办法是遵循这些库的文档。两者都有关于如何创建表单的清晰简单的演示。

      Redux Form docs

      React Redux Form docs

      我对两者都有经验,我个人选择react-redux-form 是因为它的灵活性。


      虽然回答你的问题 -

      1. 不,您根本不需要使用 this.state 来处理表单,因为它都是在 redux 状态下处理的。
      2. 要禁用表单组件,请阅读this。这是使用 disabled 属性的 Control 组件上的文档
      3. 不用担心blurfocus。这些不会影响您的表现
      4. 您已经在组件的模型中定义了user.firstName。请阅读模型上的this 页面。
      5. 如上所述,我推荐react-redux-form

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2023-03-23
        • 1970-01-01
        • 2014-07-25
        • 1970-01-01
        • 2013-05-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多