我正在使用react路由器和gridjs,并希望在一个单元格内显示一个链接,用户可以单击该链接以转到详细页面。
作为第一种方法,我尝试使用列格式化程序:
import { Link } from "react-router-dom";
import { Grid } from 'gridjs-react';
const linkFormatter = (cell, row) =>
_(
<Link to={`/jobs/${row.cells[1].data}`} className="font-bold">
{cell}
</Link>
);
...
<Grid
data={[
['Job A', '123'],
['Job B', '124']
]}
columns={{
{name: 'Name', formatter: linkFormatter},
'Job Id'}}
/>我得到以下错误:Error: Invariant failed: You should not use <Link> outside a <Router>
下面是我尝试使用useHistory的另一种方法
import { useHistory } from "react-router-dom";
const CellLink = ({ item }) => {
let history = useHistory();
function handleClick() {
history.push(`/jobs/${item.jobId}`);
}
return (
<button onClick={handleClick} className="font-bold">
View
</button>
);
};
...
<Grid
data={data.map((item) => ({
...item,
button: _(<CellLink item={item} />),
}))}
columns={columns}
/>如果我在网格之外的同一组件中使用CellLink,它可以工作,但如果我在一个单元格中使用它,我会得到TypeError: Cannot read property 'push' of undefined。
有没有办法让来自react-router的<Link />或history在cell gridjs中工作?任何建议都将不胜感激。
发布于 2021-11-19 13:02:36
将历史记录作为道具发送到CellLink
import { useHistory } from "react-router-dom";
const CellLink = ({ item, history }) => {
function handleClick() {
history.push(`/jobs/${item.jobId}`);
}
return (
<button onClick={handleClick} className="font-bold">
View
</button>
);
};
...
const WrapperComponent = () => {
let history = useHistory();
return (
<Grid
data={data.map((item) => ({
...item,
button: _(<CellLink item={item} history={history} />),
}))}
columns={columns}
/>
)
}https://stackoverflow.com/questions/66544239
复制相似问题