redux-form:如果至少有一个Field无效,如何禁用提交按钮?

Chr*_*lin 14 reactjs redux redux-form react-redux

我使用redux-form渲染下面的简单形式,它运行良好.现在,我想在一个更多的情况下禁用提交按钮:如果任何Field一个有错误(即它meta.error已设置).

从lokking到文档,我想周围的人不可能<form>知道它的<Field>组件是否有错误.也许任何人都有一个想法,如何解决它就像使用一样简单disabled={hasErrors || submitting || pristine}

const EditBlogEntryForm = ({ onSubmit, reset, handleSubmit,
                         pristine, submitting, ...rest }) => {
    console.log('rest: ', rest);
    return (
        <form onSubmit={handleSubmit(onSubmit)}>
            <div className="form-group">
                <Field name="title"
                    type="text"
                    component={renderField}
                    label="Titel"
                    className="form-control"
                    placeholder="Titel eingeben..." />
            </div>
            <div className="form-group">
                <Field name="text"
                    component={renderTextArea}
                    label="Text"
                    className="form-control"
                    placeholder="Textinhalt eingeben..." />
            </div>  
            <div className="form-group">
                <Field name="image"
                    type="text"
                    component={renderField}
                    label="Bild-URL:"
                    className="form-control"
                    placeholder="Bildadresse eingeben..." />
            </div>  
            <div>
                <button type="submit" className="btn btn-default"
                    disabled={submitting || pristine}>
                    Blogeintrag speichern
                </button>
                <button type="button" className="btn btn-default"
                    disabled={pristine || submitting}
                    onClick={reset}>
                    Formular leeren
                </button>
            </div>
        </form>
    );
};
Run Code Online (Sandbox Code Playgroud)

mas*_*ush 21

不要滥用你需要的状态只需要为每个setState组件使用this.props再渲染一次

const {invalid} = this.props

return(
<button type="submit" className="btn btn-default"
     disabled={invalid|| submitting || pristine}>
     Blogeintrag speichern
 </button>)
Run Code Online (Sandbox Code Playgroud)

更多文档:https: //redux-form.com/6.0.0-alpha.4/docs/api/props.md/


Ala*_*air 2

你应该能够做的只是调用一个变量,Errors一旦你的 api 调用返回错误,该变量就会为 true

 constructor(super) {
      this.state = {
         errors: false,
      }
 }

 componentWillReceiveProps(nextProps) {
     const that = this;
     if (nextProps.errors) {
        that.setState({errors: true})
     }    
 }

 <button type="submit" className="btn btn-default"
     disabled={this.state.errors || submitting || pristine}>
     Blogeintrag speichern
 </button>
Run Code Online (Sandbox Code Playgroud)

  • 正如@masoud-soroush 所提到的,最好不要滥用国家。请参阅他的[解决方案](/sf/answers/3333229511/)。 (2认同)