2017-03-16 69 views
0

訪問狀態和形狀值I具有以下Redux的形式(6.5.0)的源代碼:終極版形式:上handleSubmit

class MyForm extends Component { 
 

 
\t handleSubmit() { 
 
    \t \t console.log("Inside the handleSubmit of the MyForm Component where state is accessible", this.state.MyStateElement); 
 
\t } 
 

 
\t function render() { 
 
\t \t return (
 
    \t \t <<<< \t CHOICE 1: >>>> 
 
     <form onSubmit={handleSubmit(this.handleSubmit.bind(this))} > 
 

 
    \t \t <<<< \t CHOICE 2: >>>> 
 
     <form onSubmit={handleSubmit(submit)}> 
 

 
\t \t \t \t {someFields} 
 
\t \t \t </form> 
 
\t \t); 
 
\t } 
 
} 
 

 
function submit(values) { 
 
\t console.log("submit function outside the MyForm Component where form values are accessible but the State is NOT accessible", values); 
 
\t // values correspond to every checkbox, radio button inside MyForm 
 
}

有一個MyForm的組件。它內部有一個簡化形式。現在在反應組件中定義了一個handleSubmit()函數。在反應組件外部定義了一個submit()函數。現在我可以爲表單標籤啓用CHOICE 1或CHOICE 2定義。如果我啓用第一個,則會調用反應組件內的handleSubmit。在這裏,我可以訪問this.state,但無法訪問表單中的各個字段(除非我可以手動將每個字段映射到全局狀態,對於我擁有的幾十個字段,我無法明確地做到這一點) 。如果啓用CHOICE 2,則所有字段的值都正確地進入submit函數。但是我無法訪問submit函數中的this.state

我的問題是:有沒有辦法獲得字段值以及this.state在handleSubmit /提交功能?

回答

1

好吧,我找到了一個解決方案(不知道這是否是最好的)。我只需要將values參數添加到handleSubmit函數中。所以更新的來源將是:

​​

1

另一種解決辦法是......

1)當你與reduxForm包裹表單組件指定onSubmit選項。

class myForm extends React.Component {} 
 

 
export default reduxForm({ 
 
    form: 'myForm', 
 
    onSubmit: function(values) { console.log('hello', values) } 
 
})(myForm);

2),此功能可用內部組件作爲this.props.handleSubmit所以你仍然可以編寫自己的提交處理程序,並調用this.props.handleSubmit裏面。

class myForm extends React.Component { 
 
    myOwnSubmitHanlder() { 
 
    console.log('hello', this.state); 
 
    this.props.handleSubmit() 
 
    } 
 
    
 
    render() { 
 
    return (
 
     <form onSubmit={this.myOwnSubmitHanlder}></form> 
 
    ) 
 
    } 
 
}

+0

感謝。這種方法有什麼好處嗎?是否有關於在哪些功能上應該採取什麼行動的指導原則?沒有一個功能不是更清晰的代碼?我不是試圖解開你的解決方案,而是試圖更好地理解。 –

+0

我對您的問題沒有明確的答案。我不是一名職業球員,只是幾次嘗試反應。你的解決方案也很好,但這是一個選擇的問題 – disstruct

+0

非常感謝。我會等到明天再看看有沒有更好的解決方案。 –