问题描述
我在我的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")
);
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} />
中隐藏/删除它?
解决方法
通过将以下内容添加到BookRead.js组件中来解决:-
useEffect(() => {
if (window.Tawk_API) {
window.Tawk_API.hideWidget();
}
return () => {
if (window.Tawk_API) {
window.Tawk_API.showWidget();
}
};
},[]);
,
https://developer.tawk.to/jsapi/处的API文档建议您可以使用Tawk_API.showWidget();
和Tawk_API.hideWidget();
来显示和隐藏小部件。
React-Router提供了一个useLocation
钩子,可用来确定位置何时更改。
将这两个放在一起,您应该能够获得想要的效果。