【问题标题】:React router pass callback with current route to child component反应路由器将当前路由的回调传递给子组件
【发布时间】:2023-03-25 09:57:01
【问题描述】:

我正在使用 react 和 react 路由器。我的一些组件定义了子路由,因此我想向它们传递一个回调,以便返回到特定的路由/组件。我想避免将字符串传递给特定路由(因为代码中发生路由更改时的依赖关系)。所以我更喜欢传递一个回调并用 match.url 的值填充它。

但这不起作用:match.url 总是引用当前路由,而不是传递值。

父组件(简化):

export class ParentComponent extends React.Component {
  render() {
    const { history, match, contentId } = this.props;

    return (
      <div>
        <div>
          <div>Block 1</div>
          <div>Block 2</div>
          <div>Block 3</div>
        </div>
        {contentId && <MyChildComponent content={contentId} goBack={() => history.push(match.url)} />}
      </div>
    );
  }
}

我的子组件(简化):

export class MyChildComponent extends React.PureComponent {
  render() {
    return (
      (
        <React.Fragment>
          <div role="dialog" onClick={this.props.goBack} />
        </React.Fragment>),
    );
  }
}

我的路由器:

const Routes = () => (
  <Router history={createBrowserHistory()}>
    <div>
      <Route path="/result/:contentId?" component={ParentComponent} />
    </div>
  </Router>
);

所以当我转到 /result 时,我看到 - 正如预期的那样 - 除了子组件之外的所有内容。导航到 /result/someId 时,我看到了子组件,但 goBack 仅引用当前页面而不是上一页。

【问题讨论】:

    标签: javascript reactjs callback react-router


    【解决方案1】:
    constructor(props){
       super(props);
       this.goBack = this.goBack.bind(this);
    }
    
    goBack(){
        this.props.history.goBack(); // You're not calling it from history
    }
    
    .....
    
    <button onClick={this.goBack}>Go Back</button>
    

    【讨论】:

    • 我编辑了我的问题,因为我认为存在误解。我不想通过 history.goBack。我想传递一个在传递函数时返回当前 URL 的任意函数。我想为此使用 match.url 以避免依赖于具体的路由器实现(如果 URL 稍后更改,代码应该仍然有效)。
    • 好提示,是的,我试过了。所有与路由器相关的道具的问题是它们会在子元素中的路由更改时更新。最后,我只是将父路由存储为组件创建时的状态。
    【解决方案2】:

    我认为您正在使用push 导航到另一条路线。因此,当您执行history.push('/result/someId') 时,您正在向历史堆栈添加另一个条目,因此goBack 将导航到堆栈中的前一个条目/result。它就像您是一个普通网站并单击一个链接一样工作 - 即使更改的是一些动态参数,您仍然可以返回。

    如果您不想添加历史堆栈,请使用 - history.replace('/result/someId')

    navigating with history

    【讨论】:

    • 感谢您的回答。在历史记录中添加另一条路线很好。但我想避免传递硬编码字符串,因为将来路由可能会发生变化。相反,我想在将 match.url 传递给子组件时传递它的具体值(而不是在以后的 URL 更改时更新)。
    【解决方案3】:

    我发现我的核心问题是我需要父组件中至少一部分子路由。当子路由发生变化时,这也会导致父组件中的路径道具发生变化。

    我的解决方案:将当前位置存储在父组件的构造函数中,并将其作为 prop 传递给子组件以供参考。它可以工作,但缺点是不能直接访问子组件路由,因为它们不会引用正确的父路径。对于我的用例,这很好,但欢迎改进。

    父组件

    export class ParentComponent extends React.Component {
        constructor(props) {
            super(props);
            this.location = this.props.location.pathname;
        }
    
        render() {
          return (
              {contentId && <MyChildComponent content={contentId} goBack={() => 
              history.push(this.location)} />}
          )
        }
    

    【讨论】:

      猜你喜欢
      • 2015-09-01
      • 2020-03-26
      • 2016-05-26
      • 2019-08-15
      • 2018-12-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-08-19
      相关资源
      最近更新 更多