如何将状态从父compont传递到路径中的子组件(react-route-dom)reactjs

时间:2017-05-04 12:28:16

标签: reactjs react-router-dom

我是 React.js 的新手,并使用react-router-dom创建了一个小型反应应用程序。我有两个组成部分:

  1. 控制板(dashboard.js)
  2. 信息(information.js)
  3. 和一个主要的组件应用(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 个答案:

答案 0 :(得分:2)

父组件中,您可以发送此类道具

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

答案 1 :(得分: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;