在React 16和Bootstrap 4中,如何将引导选项卡组件中的每个选项卡映射到URL



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

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?现在我有";主页";以及";人"选项卡。我想把";主页";选项卡到"/编辑/<我的实体id/home";以及";人"选项卡到"/编辑/<我的实体id/人";。然后,如果有人访问这两个URL中的任何一个,就会预先选择相应的选项卡。

使用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>
);
};

相关内容

  • 没有找到相关文章

最新更新