【问题标题】:Pass React route component to parent component props function将 React 路由组件传递给父组件 props 函数
【发布时间】:2019-06-20 13:06:42
【问题描述】:

如果这听起来很愚蠢,我会做出反应并原谅我,但我正在努力解决这个问题。

我的组件结构是这样的:

  • 仪表板
    • 计费
    • 发票

我想要它,以便当您单击计费内的发票链接时,发票组件会呈现在位于仪表板中的 div 中。

  • 仪表板
  • 计费____^
  • 发票>>>

我不知道我的方法是否正确,我有什么问题,或者它是否完全不正确,我需要重新考虑我的理解。

仪表板:

<Route
    path="/dashboard/billing"
    render={() => (
        <Billing
            togglePanel={this.togglePanel}
            fillPanel={this.fillPanel}
        />
    )}
/>

BILLING:

<Route
    path="/dashboard/billing/invoice/:id"
    render={props => (
        <Invoice {...props} />
    )}
/>

Inside billing there is a list of Links as:

<Link
    onClick={event => {
        this.props.togglePanel();
    }}
    className="item"
    to={`/dashboard/billing/invoice/${d.id}`}
>
    View
</Link>

所以我们很清楚我正在使用:

从“react-router-dom”导入 { Link, Route };

在仪表板中,我有一个要填充发票组件的 div。

fillPanel() 函数改变 Dashboard 中的状态,进而将目标 div 的内容更改为传递的任何内容(这只是我的尝试)。

我知道如何在切换等上显示和隐藏,所以这不是问题,我只想知道在单击 Billing 中的项目后呈现时,如何使用 Invoice 组件填充 Dashboard 中的目标 div。

【问题讨论】:

    标签: javascript node.js reactjs react-router react-router-dom


    【解决方案1】:

    您不需要为您的用例渲染路由。据我所知,每当您单击Billing.js 中的链接(来自链接列表)时,您只需要在 div 中显示Invoice.js

    你可以做的是:

    <Link
      onClick={event => {
        this.props.togglePanel();
      }}
      className="item"
      to={`/dashboard/billing/invoice/${d.id}`}
    >
      View
    </Link>
    

    用途:

    <div 
      onClick={event => {
        this.props.togglePanel();
      }}
      className="item"
    > View 
    </div>
    

    并且,而不是:

    <Route
      path="/dashboard/billing/invoice/:id"
      render={props => (
        <Invoice {...props} />
      )}
    />
    

    用途:

    <div className="div-where-you-want-to-show-the-invoice">
      <Invoice {...props, d.id}/>
    </div>
    

    【讨论】:

    • 这确实有效,感谢您的帮助,但我希望用户能够复制特定发票的链接,因此我使用路由。显然我可以推送带有历史记录的路由,但是当用户访问该 url 时,我怎样才能使其打开?
    • 在这种情况下: 1:在发票路由上也调用相同的组件。 2:在您的componentDidMount 生命周期方法中,读取路由参数。 3:使用路由参数在div-where-you-want-to-show-the-invoice中相应地获取/打开您的发票
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-31
    • 1970-01-01
    • 2017-11-17
    相关资源
    最近更新 更多