首页 > 解决方案 > React 组件,使用嵌套组件访问 this.props

问题描述

我遇到了一个小挑战,那就是如何让子组件访问 this.props 之类的东西(特别是寻找 this.props.history)。我的代码本质上是;

// app.js, setup a router...
return (
  <Router>
    <Route path="/componenta" component={ComponentA}/>
  </Router>
);
// Component A has access to this.props
class ComponentA extends Component {
  componentDidMount() {
    console.log('The props are ', this.props);
  }

  render() {
    return (
      <div>
         <h1>Hello from Component A</h1>
         <ComponentB/>
      </div>
    );
  }
}
// ComponentB does not have access to this.props, 
// and I know it is because it is a sub-component here.
class ComponentB extends Component {
  componentDidMount() {
    console.log('The props are ', this.props);
  }

  render() {
    return (
      <div>
        <h1>Hello from Component B</h1>
      </div>
    );
  }
}

我觉得这是我想念的简单的东西,有什么建议吗?

谢谢。

标签: reactjsreact-router

解决方案


欢迎来到 SO,我看到你没有传递任何东西propComponentB所以你必须做这样的事情;

<ComponentB history={this.props.history}/>

然后你就可以history在你的ComponentB


推荐阅读