【问题标题】:Navigating Using React Router From a Button Outside the React App从 React 应用程序外部的按钮使用 React Router 导航
【发布时间】:2020-12-16 17:32:41
【问题描述】:

我有一个简单的演示反应应用程序,它使用 react-router-dom (5.2) 来显示 3 个“页面”之一。

应用包含在有按钮的页面上:

index.html:

<button data-app-button data-sku='woo-beanie'>Click Me</button>

index.js:

import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';

document.addEventListener('click', function (event) {    
    if (event.target.closest('button[data-app-button]')) {
      // send instructions to react
    }
});

ReactDOM.render(
  <React.StrictMode>
    <App />
  </React.StrictMode>,
  document.getElementById('root')
);

我希望能够通过按钮数据属性导航到反应站点中的页面。 react 和 react-router 是怎么做到的?

更新

@Doppoio 的解决方案有效 - 只要我在我的 react 应用程序中的不同“页面”上。但是我有这样的路线:

  <Route
    path="/tryon/:id/:product_sku?">
  </Route>

如果我从 /faqs 路径开始在应用程序中,并且我的外部按钮导航到 /tryon/242/jumper-23 我的组件是 product_sku 属性。

但是,当我在 /tryon/242 的应用程序页面上,然后单击外部按钮导航到 /tryon/242/jumper-23 时,组件应该知道 jumper-23 可选参数。目前不是。

如何让 Tryon 组件仅检测可选参数的 url 变化?

【问题讨论】:

    标签: reactjs


    【解决方案1】:

    在路由器下的代码中的某处,您可以将历史记录添加到窗口对象。并从那里调用它。

    const SomeComponentInsideRouter = () => {
      const history = useHistory();
      useEffect(() => {
        window.reactHistory = history; // Add reference to history via window object.
      }, []);
      return null;
    };
    

    并通过 window.reactHistory 调用它

    document.addEventListener("click", function (event) {
      if (event.target.closest("button[data-app-button]")) {
        // send instructions to react
        window.reactHistory.push("/about");
      }
    });
    

    这里是沙盒链接 https://codesandbox.io/s/happy-ganguly-b0u2o?file=/src/index.js

    更新提及更改的道具:

    可以使用 componentDidUpdate 检测到 props 的变化

    https://reactjs.org/docs/react-component.html#componentdidupdate

    【讨论】:

    • 谢谢。那么历史只是进入推送的网址的一种方式吗?如果我需要从按钮数据属性中传递参数,我将它们放在推送到历史记录的路径中吗?然后如何访问它们?
    • 差不多,是的。 react-router 可以读取 url 参数或查询参数。飞走。
    • 我实现了这个,效果很好。但是,如果我尝试在反应应用程序中导航到相同的 url,但使用可选属性,它不会注册更改。我必须在应用程序的不同页面上,以便在导航时呈现组件。有什么想法吗?
    • 可选属性是指查询参数,如/about?page=1 ?
    • 不,我已经用更多细节更新了这个问题。
    猜你喜欢
    • 2020-05-18
    • 2016-12-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-06-22
    • 1970-01-01
    • 1970-01-01
    • 2018-12-16
    相关资源
    最近更新 更多