2017-01-02 86 views
1

我的代碼的重要部分看起來像。訪問從路由器傳遞到表格的孩子的值

路線:

<Route path="/login" component="Login"> 
    <Route path="/login/lender" component="LenderLogin"/> 
    <Route path="/login/customer" component="CustomerLogin"/> 
</Route> 

渲染內登錄:

<div> 
    <form> 
    {/*All my common inputs*/} 
    {/*Link to Customer and Lender*/} 

    {this.props.children} 
    <input type="submit"/> 
    </form> 
</div> 

CustomerLogin和LenderLogin裏面有他們自己的投入。在提交表格時,如何將LenderLoginCustomerLogin數據輸入Login

+0

您使用哪種機制來保留表單值? (你標記了'redux',所以我假設你保持一箇中央狀態?) –

回答

1

有2個解決方案。

  1. 在反應中,您可以使用道具來傳遞數據/回調。 (GOOD) 您可以將回調傳遞給兒童組件,這些兒童組件可在兒童更改數據 時調用。

    對於更多的細節。 http://andrewhfarmer.com/component-communication/

  2. 使用ref(BAD) 將屬性ref =「customerComponent」分配給您的客戶,然後將ref =「lenderComponent」分配給另一個。然後可以在那些返回值的組件中定義方法。 當需要時,您可以調用customComponent.getMyValue()中的方法來獲取值。
    https://facebook.github.io/react/docs/refs-and-the-dom.html

0

也許,你應該使用一個零件形狀這裏面。例如:

my_component.js

import FormComponent from './form_component'; 

class MyComponent extends React { 
    render() { 
    return(
     <div> 
     <FormComponent data={this.state.data} /> 
     </div> 
    ); 
    } 
} 

export default MyComponent; 

form_component.js

const FormComponent = ({data}) => { 
    return(
    <div> 
     <form> 
     ... 
     </form> 
    </div> 
); 
} 

export default FormComponent; 

但是,如果你喜歡用孩子,你可以使用IndexRoute

import { Router, Route, IndexRoute, browserHistory } from 'react-router'; 

<Route path="/login/lender" component="LenderLogin"> 
    <IndexRoute component={FormComponent)} /> 
<Route> 
0

如果你正在使用像Redux的狀態管理器,您應該存儲從您的LenderLoginCustomerLogin有數據(通過調度事件),然後Login組件內檢索它(與react-reduxconnect()方法。