【问题标题】:How to pass state from parent Component to child component in route (react-route-dom) reactjs如何将状态从父组件传递到路由中的子组件(react-router-dom)react js
【发布时间】:2017-10-02 15:15:51
【问题描述】:

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

  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 组件发送到仪表板和信息,但我想发送状态。有人可以帮助我,我如何将状态从父组件发送到子组件?

【问题讨论】:

    标签: reactjs react-router-dom


    【解决方案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;
    

    【讨论】:

      【解决方案2】:

      父组件你可以像这样发送道具

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

      【讨论】:

      • 很棒 } />
      • 如果可行,您可以接受我的回答,这样如果您将此答案标记为已接受,未来的用户就可以从这个问题中获得帮助。
      猜你喜欢
      • 2017-05-18
      • 1970-01-01
      • 2018-02-12
      • 1970-01-01
      • 1970-01-01
      • 2022-07-15
      • 2017-12-06
      • 2020-07-04
      • 1970-01-01
      相关资源
      最近更新 更多