简体   繁体   English

如何根据 url 路由制作“全局”组件渲染内容?

[英]How to make a “global” component render content based on url route?

I have a FAQ button that's fixed onto the bottom right corner of the screen (it's on every screen of the website), when clicked a modal pops out displaying frequent asked questions and their respective answers, I'd like the modal to display different content based on the url that the user is on.我有一个固定在屏幕右下角的常见问题解答按钮(它在网站的每个屏幕上),当点击一个模式弹出显示常见问题及其各自的答案时,我希望模式显示不同的内容基于用户正在使用的 url。

For example: if the user is on www.example.com/signup then the modal would render the content specific to the sign up process, and when the user is on www.example.com/shop only the faq's related to shopping should appear.例如:如果用户在www.example.com/signup上,则模式将呈现特定于注册过程的内容,而当用户在www.example.com/shop上时,只会出现与购物相关的常见问题. This should be taking into account the first part of the url params, so if a user goes to www.example.com/shop/294594 (or any other route that stars with /shop) then the modal still displays the same content as for www.example.com/shop .这应该考虑到 url 参数的第一部分,因此如果用户转到www.example.com/shop/294594 (或任何其他以 /shop 为星号的路线),那么模态仍然显示与www.example.com/shop

Is there any good way to to this with react-router (or any other alternative)? react-router(或任何其他替代方案)有什么好的方法吗? I did some research into react-router useParams hook but I'm not sure if it's the go-to solution since I'm just a beginner in routing.我对 react-router useParams 钩子进行了一些研究,但我不确定它是否是首选解决方案,因为我只是路由的初学者。 Thanks for your time!谢谢你的时间!

You can create a FAQ component like this https://codesandbox.io/s/react-router-tgh8c?file=/components/FAQ.js您可以像这样创建一个FAQ组件https://codesandbox.io/s/react-router-tgh8c?file=/components/FAQ.js

import React from "react";
import { useLocation } from "react-router-dom";

const SignupFaq = () => <p>Sign up questions</p>;
const ShopFaq = () => <p>Shop questions</p>;

const faqs = {
  signup: {
    component: <SignupFaq />
  },
  shop: {
    component: <ShopFaq />
  }
};

function FAQ() {
  const { pathname } = useLocation();

  const { component } = faqs[pathname.split("/")[1]];

  const [modal, showModal] = React.useState(false);

  return (
    <React.Fragment>
      <button onClick={() => showModal(!modal)}>FAQ</button>
      <div className="modal">{modal && <div>{component}</div>}</div>
    </React.Fragment>
  );
}

export default FAQ;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM