2017-05-03 26 views
8

我正在渲染下面的简单形式使用redux形式,它的工作很好。现在,我希望在另外一种情况下禁用提交按钮:如果任何Field的错误(即设置了meta.error)。redux-form:如果至少有一个字段无效,如何禁用提交按钮?

从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> 
    ); 
}; 
+0

你能做的仅仅是添加您自己的变量,并把它放在什么状态像'错误'。一旦这个值为false,那么你可以按照@ masoud-soroush提到的提交按钮 – Alastair

回答

3

,你应该能够做的仅仅是有一个变量称为Errors,这将是真正的是什么,一旦你的API调用回来了一个错误

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> 
+0

,最好不要滥用状态。请参阅他的[解决方案](https://stackoverflow.com/a/47617564/1111215)。 –

0

Alastair指出我正确的方向(谢谢你!)。我想这是其中一个本地UI相关状态实际上非常有用的情况之一。所以我将SFC重构为一个反应类。这班constructorcomponentWillReceiveProps是这样的:

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

componentWillReceiveProps(nextProps) { 
    if (nextProps.invalid) { 
     this.setState({errors: true}); 
    } else { 
     this.setState({errors: false}); 
    } 
} 

现在使用this.state.errors停用了正在完美的按钮。正如你所看到的,我不得不使用invalid形式缩减形式,因为它的error道具总是未定义的,如果表单有效,不要忘记重新设置它。此外,我不知道,为什么您在回答中将this参考文献复制到that中。它不会改变任何行为,因为它仍然指向同一个对象。

7

不要滥用你只需要使用this.props 每个组件的setState更多的时间用于国家将呈现

const {invalid} = this.props 

return(
<button type="submit" className="btn btn-default" 
    disabled={invalid|| submitting || pristine}> 
    Blogeintrag speichern 
</button>) 
相关问题