2015-11-03 33 views
3

由於我對React生態系統非常陌生,因此我的描述和做事方式可能會有所改變,但我希望您能跟上我的問題。redux-form:動態定義handleSubmit

我有一個父組件,它獲取從路由器注入的表單並將狀態和動作創建者映射到屬性。

Container.js

import * as actionCreators from "../actionCreators"; 

export default class ComponentA extends React.Component { 

    render() { 
    return (
     <div className="ComponentA"> 
     {this.props.children} //<--Form 
     </div> 
    ); 
    } 
} 

function mapStateToProps(state) { 
    return { 
    listItems: state.get("listItems") 
    }; 
} 

export const Container = connect(mapStateToProps, actionCreators)(ComponentA); 

其獲取與{this.props.children}渲染是以下形式的組件。

Form.js

class Form extends React.Component { 

    static propTypes = { 
    fields: PropTypes.object.isRequired, 
    handleSubmit: PropTypes.func.isRequired 
    }; 

    render() { 
    const { fields: {title, description}, handleSubmit} = this.props; 
    return (
     <div className="create-project-form"> 
     <h1>Create Project</h1> 
     <form onSubmit={handleSubmit}> 
      <label htmlFor="title">Title</label> 
      <input type="text" name="title" id="title" className="form-control"/> 
      <label htmlFor="description">Description</label> 
      <textarea name="description" id="" cols="30" rows="10" className="form-control"></textarea> 
      <button className="btn btn-danger" onClick={handleSubmit}>Create</button> 

     </form> 
     </div> 
    ) 
    } 
} 

export default connectReduxForm({ 
    form: "from", 
    fields: ["title", "description"] 
})(Form); 

路由器

const routes = <Route component={App}> 
    <Route path="/" component={Container}/> 
    <Route path="/a" component={Container}> 
    <Route path="https://stackoverflow.com/a/create" component={Form}/> 
    </Route> 
</Route>; 

render(
    <div> 
    <Provider store={store}> 
     <Router>{routes}</Router> 
    </Provider> 
    </div>, 
    document.getElementById("content")); 

問題是handleSubmit不是不確定的,但它是不我的行動。我其實並不認爲它神奇地設置爲正確的actionCreator,但我如何傳遞函數?我嘗試了操作名稱而不是handleSubmit,但是函數未定義。我看到的每個示例都將handleSubmit函數手動傳遞給Form組件,但我無法這樣做,因爲表單由Router設置。

感謝

回答

7

兩件事情:

  1. 您需要將字段信息傳遞給你的<input>

<input type="text" {...title} // <-------- that (it contains the "name" prop) className="form-control"/>

  • 您可以通過任何匿名函數來handleSubmit
  • <form onSubmit={handleSubmit(data => { // do your submit stuff here and return a Promise if you want the // this.props.submitting flag to be set for the duration of the promise })}>

    這是否幫助? See also

    +1

    謝謝。據我瞭解,我應該注入一個函數,在提交時執行。我可以在你的例子(2)中直接在表單組件內部實現這個函數,但是我似乎無法將一個函數傳遞給這些道具。類似於

    。我認爲這是一個普遍的縮減問題,並不是特定於縮減形式,但也許你看到了什麼問題。我可以傳遞一些信息給{this.props.children}嗎?我實際上認爲react-redux的連接會照顧到這一點,但事實並非如此。 – KenavR

    +1

    @KenavR稍微遲了一點,但是要傳遞被調用的函數,您將它作爲'onSubmit'傳遞,然後綁定到表單中的{handleSubmit},onSubmit將自動調用 – Tom