[英]How to change routes in gatsby without Link component?
I have a controlled form in react.我在反应中有一个受控的形式。 When the user submits the form, in the
handleSubmit
run, In that function I want to redirect/take them to a new url or page, where url is same as their input value.当用户提交表单时,在
handleSubmit
运行中,在该函数中,我想将它们重定向/带到新的 url 或页面,其中 url 与它们的输入值相同。
For example user types "hello", then when the form submits I want to take them to例如用户输入“你好”,然后当表单提交时我想带他们去
It seems like </Link>(gatsby)
component won't work in here.似乎
</Link>(gatsby)
组件在这里不起作用。 So how do I change route without a Link
Component那么如何在没有
Link
组件的情况下更改路线
This is for a search bar这是一个搜索栏
You should import the navigate API to push/replace the history stack, in order to carry out navigation.您应该导入导航 API 来推送/替换历史堆栈,以便执行导航。
import { navigate } from 'gatsby'
And this is how you can use it, on your form submit method.这就是您可以在表单提交方法中使用它的方式。 It is similar to React-Router's
history.push()
.它类似于 React-Router 的
history.push()
。
submit() {
// rest of your form logic
navigate('/hello');
}
If you wish to replace the history stack, you may use navigate('/hello', { replace: true })
instead.You may refer to the Gatsby Link documentation for more details.如果您希望替换历史堆栈,您可以使用
navigate('/hello', { replace: true })
代替。您可以参考 Gatsby Link文档了解更多详细信息。
You can use Gatsby's navigate
helper function.您可以使用 Gatsby 的
navigate
助手功能。
For example:例如:
import React, { useState } from "react"
import { navigate } from "gatsby"
const Form = () => {
const [value, setValue] = useState("")
return (
<form
onSubmit={event => {
event.preventDefault()
navigate(`/${value}`)
}}
>
{/* here goes your input that sets its value to state with `setValue` */}
</form>
)
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.