英文:
Next.js execute onClick event before href link routing
问题
以下是您要翻译的内容:
Context
我正在使用Next.js 13,并且正在使用Apollo客户端来存储一些客户端变量。
What i'm trying to do
我尝试在导航到href位置之前执行onClick函数。
My Code
<Link
href={`/session/${session.id}`}
onClick={() => {
updateDialogVars({
dialogOpen: ATTENDANCE_DIALOG,
})
}}
>
<div>
stuff
</div>
</Link>
updateDialogVars是一个mutation,用于更新Apollo客户端中的响应式变量。
Question
是否可以使用Next.js Link组件在href路由之前执行onClick事件?是更改Link为div,然后在onClick函数执行后使用next router来推送路由更改的唯一选项吗?
英文:
Context
I'm using Next.js 13. And I'm using apollo client to store some client side variables.
What i'm trying to do
I'm trying to execute the onClick function prior to navigating to the href location.
My Code
<Link
href={`/session/${session.id}`}
onClick={() => {
updateDialogVars({
dialogOpen: ATTENDANCE_DIALOG,
})
}}
>
<div>
stuff
</div>
</Link>
updateDialogVars is a mutation and updates a reactive vars in apollo client.
Question
Is it possible to use Next.js Link component and execute the onClick event before routing takes place with the href? Is the only option to change Link to a div and use next router to push the route change after the onClick function executes?
答案1
得分: 1
以下是代码的翻译部分:
This is typically achieved with a button and [router hook][1], not an anchor tag (link).
import { useRouter } from "next/router";
const SomeComponent = () => {
const router = useRouter();
const onClick = async () => {
updateDialogVars(...yourConfig);
if(someCondition) {
await router.push(`/session/${session.id}`);
}
}
return (
<button onClick={onClick}>Label</button>
)
}
You can also achieve a similar result with next/link.
import { useRouter } from "next/router";
import Link from "next/link";
const SomeComponent = () => {
const router = useRouter();
const onClick = async (event) => {
event.preventDefault();
updateDialogVars(...yourConfig);
if(someCondition) {
await router.push(event.target.href);
}
}
return (
<Link href={`/session/${session.id}`} onClick={onClick}>Label</Link>
)
}
英文:
This is typically achieved with a button and router hook, not an anchor tag (link).
import { useRouter } from "next/router";
const SomeComponent = () => {
const router = useRouter();
const onClick = async () => {
updateDialogVars(...yourConfig);
if(someCondition) {
await router.push(`/session/${session.id}`);
}
}
return (
<button onClick={onClick}>Label</button>
)
}
You can also achieve a similar result with next/link.
import { useRouter } from "next/router";
import Link from "next/link";
const SomeComponent = () => {
const router = useRouter();
const onClick = async (event) => {
event.preventDefault();
updateDialogVars(...yourConfig);
if(someCondition) {
await router.push(event.target.href);
}
}
return (
<Link href={`/session/${session.id}`} onClick={onClick}>Label</Link>
)
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论