0

我正在使用 Bootstrap 4 构建一个 React 16.13.0 应用程序。我想在特定组件 src/components/Edit.jsx 上使用 Tabs ...

import React, { useEffect, useState } from "react";
import { useParams } from "react-router-dom";
import { Tabs, Tab } from "react-bootstrap";

import FormContainer from "../containers/FormContainer";
import ListPeople from "../components/people/ListPeople";
import { DEFAULT_COUNTRY_CODE } from "../utils/constants";

const { REACT_APP_PROXY } = process.env;

const Edit = (props) => {
  const { id } = useParams();
  const [key, setKey] = useState("home");
  const [coop, setCoop] = useState(null);

  useEffect(() => {
    if (coop == null) {
      fetch(REACT_APP_PROXY + "/coops/" + id)
        .then((response) => {
          return response.json();
        })
        .then((data) => {
          const coop = data;
          coop.addresses.map((address) => {
            address.country = { code: address.locality.state.country.code };
          });
          console.log("edit cop ...");
          console.log(coop);
          setCoop(data);
        });
    }
  }, [props]);

  if (coop == null) {
    return <></>;
  }
  return (
    <div className="container">
      <h1>{coop.name}</h1>

      <Tabs id="controlled-tabs" activeKey={key} onSelect={(k) => setKey(k)}>
        <Tab eventKey="home" title="Home">
          <FormContainer coop={coop} />
        </Tab>
        <Tab eventKey="people" title="People">
          <ListPeople coop={coop} />
        </Tab>
      </Tabs>
    </div>
  );
};

export default Edit;

我还没有弄清楚如何做的事情是如何将每个选项卡映射到 URL?现在我有“家”和“人”标签。我想将“主页”选项卡映射到“/edit/<my entity id/home”,将“人员”选项卡映射到“/edit/<my entity id/people”。然后,如果有人访问这两个 URL 中的任何一个,则会预先选择相应的选项卡。

4

1 回答 1

0

react-router很容易:

import {Route} from 'react-router-dom';

const Edit = () => {
  const { id } = useParams();
  ...
  return (
    <Route path="/edit/:id/:tab">
      {({ match, history }) => {
        const { tab } = match ? match.params : {};

        return (
          <Tabs
            activeKey={tab}
            onSelect={(nextTab) => history.replace(`/edit/${id}/${nextTab}`)}
          >
            ...
          </Tabs>
        );
      }}
    </Route>
  );
};

这是一个例子

或者,如果您的父路由路径看起来像/edit/:id/:tab那样,您可以:

const Edit = () => {
  const { id, tab } = useParams();
  const history = useHistory();
  ...
  return (
    <Tabs activeKey={tab} onSelect={(nextTab) => history.replace(`/edit/${id}/${nextTab}`)}>
    // or if you wish, you can use history.push instead of history.replace
      ...
    </Tabs>
  );
};
于 2020-07-20T19:03:23.037 回答