2017-05-03 78 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>) 
相關問題