2017-02-14 52 views
0

我寫一個簡單的終極版的應用程序和組件的一個看起來像這樣終極版讀取值<INPUT TYPE =文本>

const LoginComponent = ({onLoginClick, onRegisterClick}) => (
    <div className={styles.loginDiv}> 
     <p className={standardStyles.pageTitleText}>SyncSpace</p> 
     <input type="text" placeholder="Username"/> 
     <input type="password" placeholder="Password"/> 
     <div className={styles.loginRegisterDiv}> 
      <button className={styles.loginButton} onClick={onLoginClick}>Login</button> 
      <button className={styles.registerButton} onClick={onRegisterClick}>Register</button> 
     </div> 

    </div> 
); 

在我想讀鍵入的用戶名值的單擊事件和密碼字段並將它們作爲參數傳遞給onLoginClick事件。 Redux中讀取此值的正確方法是什麼?

回答

0

我建議看看redux-form

這是一個非常活躍的項目,有一個偉大的社區來回答任何問題。

這裏是一個如何到attach a form to the redux store的例子。

使用Redux的形式,您可以將您的形式轉變到這樣的事情:

import React from 'react'; 
import { Field, reduxForm } from 'redux-form'; 

const LoginComponent = ({onRegisterClick, onLoginClick}) => (
    <form onSubmit={onRegisterClick} className={styles.loginDiv}> 
     <p className={standardStyles.pageTitleText}>SyncSpace</p> 
     <Field name="userName" component="input" type="text" placeholder="Username"/> 
     <Field name="password" component="input" type="password" placeholder="Password"/> 
     <div className={styles.loginRegisterDiv}> 
     <button type="submit" className={styles.loginButton}>Login</button> 
     </div> 
    </form> 
); 

我個人比較喜歡有註冊和登錄在兩個不同的看法動作發生,但如果你選擇有兩個在你的redux形式的按鈕,有多種方式來做到這一點。 This is a good answer on attaching the action to the onClick handlers as you do, but a modification to the action so that it takes in a parameter.

4

Redux-Form過度殺毒。你絕對是不需要任何一種庫來從窗體中讀取。

這實際上不是一個Redux問題,具體而言 - 這是一個React問題。有兩種方法可以處理React中的表單值:「受控」輸入和「不受控制」輸入。當你問「如何讀取點擊值」時,答案是「從輸入本身使用refs讀取它們」用於未受控制的輸入,以及「從組件狀態讀取值」以獲取受控輸入。

Gosha Arinich有幾篇文章解釋瞭如何在React中使用表單的基礎知識,我強烈建議您先閱讀那些文章:https://goshakkk.name/on-forms-react/。他們解釋了「受控」和「不受控制」輸入的概念,以及如何使用它們。 (Gosha也剛剛發佈了一本關於表格和React的優秀書,我也推薦它,它比博客文章更詳細:https://goshakkk.name/the-missing-forms-handbook-of-react/)。

相關問題