[英]Go to a link when clicked inside a Table.Row with onClick
I have a table and I want each row to be clickable and when you click on it to go to that link (which is different for each row).我有一个表,我希望每一行都是可点击的,当你点击它到 go 到那个链接(每行不同)。
<Table.Body>
{rows.map((row, rowIndex) => (
<Table.Row
key={idList && idList[rowIndex]}
onClick={() => {
<Link
to={
entityName && `/${entityName}/${idList[rows.indexOf(row)]}`
}
/>;
}}>
...
</Table.Row>
))}
</Table.Body>
So I did it like above, added a component but doesn't work.所以我像上面那样做了,添加了一个组件但不起作用。 It says:它说:
Expected an assignment or function call and instead saw an expression no-unused-expressions预期分配或 function 调用,而是看到一个表达式 no-unused-expressions
I'm using Table
/ Table.Row
from Semantic UI
and Link
from react-router-dom
.我正在使用Semantic UI
中的Table
/ Table.Row
和react-router-dom
中的Link
。 I cannot change the Table
but the Link
component isn't mandatory.我无法更改Table
,但Link
组件不是强制性的。 It would be great anyway if it can redirect to that link when it's clicked.无论如何,如果它可以在单击时重定向到该链接,那就太好了。
Is it any way to do this?有什么办法吗?
One way would be is to use the history to navigate from the component.一种方法是使用历史从组件导航。 To get the history object, you either need to use the useHistory()
hook which is available from react-router:5.1.0 or if you are using a older version of react-router要获取历史 object,您需要使用可从react-router:5.1.0获得的useHistory()
挂钩,或者如果您使用的是旧版本的 react-router
Functional功能性
const onNavigate = (entityName, idList) => () => {
entityName && history.push( && `/${entityName}/${idList[rows.indexOf(row)]}`) // change accordingly
}
Class Class
onNavigate = (entityName, idList) {
return function () {
return entityName && this.props.history.push( && `/${entityName}/${idList[rows.indexOf(row)]}`) // change accordingly
}
}
This method returns a function reference, so that the onCLick
prop doesn't trigger it on render and some_props
will be visible in the inside function thanks to Closures此方法返回 function 引用,因此onCLick
道具不会在渲染时触发它,并且some_props
将在内部function中可见
onClick
method:您将方法传递给onClick
方法:<Table.Body>
{rows.map((row, rowIndex) => (
<Table.Row
key={idList && idList[rowIndex]}
onClick={onNavigate(enitityName, idList)}
>
...
</Table.Row>
))}
</Table.Body>
this way the click handler will receive the a function reference and should navigate to the according url这样,点击处理程序将收到 function 引用,并应导航到相应的 url
Using react-router
to link inside the react application you can use the useHistory
hook and push the new path.使用react-router
链接到 react 应用程序内部,您可以使用useHistory
挂钩并推送新路径。
import { useHistory } from "react-router-dom";
function Component() {
let history = useHistory();
return (
<Table.Body>
{rows.map((row, rowIndex) => (
<Table.Row
key={idList && idList[rowIndex]}
onClick={() =>
history.push(
entityName && `/${entityName}/${idList[rows.indexOf(row)]}`
)
}
>
...
</Table.Row>
))}
</Table.Body>
);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.