2

我在我的 reactjs 应用程序上使用 tawk.io 聊天:- 这是我的 index.js 文件的内容:-

import React from "react";
import ReactDOM from "react-dom";
import App from "./App";
import { BrowserRouter, Switch, Route } from "react-router-dom";
import BookRead from "./pages/BookRead";

ReactDOM.render(
  <React.StrictMode>
    <BrowserRouter>
      <Switch>
        <Route exact path="/view/:id/:section/:part" component={BookRead} />
        <Route component={App} />
      </Switch>
    </BrowserRouter>
  </React.StrictMode>,
  document.getElementById("root")
);

App.js 组件文件内容:-

import React, { useEffect, useState } from "react";
import { Route } from "react-router-dom";
import Login from "./pages/Login";
import Account from "./pages/Account";
import Contact from "./pages/Contact";
import Home from "./pages/Home";

function App(props) {

  useEffect(() => {
    var Tawk_API = Tawk_API || {},
      Tawk_LoadStart = new Date();
    (function () {
      var s1 = document.createElement("script"),
        s0 = document.getElementsByTagName("script")[0];
      s1.async = true;
      s1.src = "https://embed.tawk.to/5a624e/default";
      s1.charset = "UTF-8";
      s1.setAttribute("crossorigin", "*");
      s0.parentNode.insertBefore(s1, s0);
    })();
  }, []);

  return (
    <div className="content">
      <div className="container">
        <Route exact path="/" component={Home} />
        <Route path="/contact-us" component={() => <Contact user={user} />} />
          )}
        />
        <Route path="/account" component={Account} />
      </div>
    </div>
  );
} 
export default App;

如何在 App.js 路由内的所有组件中显示聊天小部件并从路由中隐藏/删除它<Route exact path="/view/:id/:section/:part" component={BookRead} />

4

2 回答 2

3

通过将以下内容添加到 BookRead.js 组件来解决:-

useEffect(() => {
    if (window.Tawk_API) {
      window.Tawk_API.hideWidget();
    }
    return () => {
      if (window.Tawk_API) {
        window.Tawk_API.showWidget();
      }
    };
  }, []);
于 2020-09-28T22:27:18.480 回答
0

https://developer.tawk.to/jsapi/上的 API 文档建议您可以使用Tawk_API.showWidget();andTawk_API.hideWidget();来显示和隐藏小部件。

React-Router 提供了一个useLocation钩子,您可以使用它来确定位置何时更改。

把这两者放在一起,你应该能够得到你想要的效果。

于 2020-09-26T10:31:18.450 回答