2017-05-04 82 views
2

我是的新手,使用react-router-dom創建了一個小型反應應用程序。其中我有兩個組成部分:如何將父狀態從父組件傳遞到路由中的子組件(react-route-dom)reactjs

  1. 控制板(dashboard.js)
  2. 信息(information.js)

和一個主組件應用(App.js),其中我我正在使用react-router-dom

<Route exact path="/dashboard" render={props => <Dashboard someProp="2" {...props} />} /> 
<Route exact path="/information" render={props => <Information someProp="2" {...props} />} /> 

我能夠從App組件發送道具到儀表板和信息,但我想發送狀態。有人可以幫助我,我怎樣才能從父組件發送狀態到子組件?

回答

2

父組件您可以發送道具這樣

<child prop1 = {this.state.stateName} /> 
+1

大 <路線確切路徑= 「/儀表板」 渲染= {道具=><控制板someProp = { this.state.open} {... props} />} /> –

+0

如果有效,您可以接受我的回答,以便將來的用戶可以從此問題獲得幫助,如果您將此答案標記爲已接受。 –

1

使用上面的回答我張貼完整的代碼,使用戶更能夠理解這一點。

App.js文件

class App extends React.Component { 
constructor(props) { 
    super(props); 
    this.state = {open: false}; 
    this.state = {message: "StackOverflow"}; 
    } 

return (
     <Router> 
      <div> 
      <AppBar title="App" onLeftIconButtonTouchTap={this.handleToggle} /> 

      <Drawer containerStyle={{height: 'calc(100% - 64px)', top: 64}} docked={true} width={200} open={this.state.open} zDepth={2}> 
       <Link to="/dashboard" style={{ textDecoration: 'none' }}><MenuItem>Dashboard</MenuItem></Link> 
       <Link to="/information" style={{ textDecoration: 'none' }}><MenuItem>Information</MenuItem></Link> 
      </Drawer> 

      <Route exact path="/dashboard" render={props => <Dashboard someProp={this.state.message} {...props} />} /> 
      <Route exact path="/information" render={props => <Information someProp={this.state.message} {...props} />} /> 
      </div> 
     </Router> 
    ); 
} 

Dashboard.js

import React from 'react'; 


class Dashboard extends React.Component { 

    constructor(props) { 
    super(props); 
    } 

    render() { 
    console.log(this.props); 
    const {styleFromProps} = this.props; 
    const contentStyle = { ...styleFromProps, transition: 'margin-left 450ms cubic-bezier(0.23, 1, 0.32, 1)' }; 

    return (
      <div style={contentStyle}><h1> Hello {this.props.someProp}</h1></div> 
    ); 
    } 
} 

export default Dashboard; 
+0

很好,謝謝 –

相關問題