英文:
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.
For example user types "hello", then when the form submits I want to take them to
http://example.com/hello
It seems like </Link>(gatsby)
component won't work in here. So how do I change route without a Link
Component
This is for a search bar
英文:
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.
For example user types "hello", then when the form submits I want to take them to
> http://example.com/hello
It seems like </Link>(gatsby)
component won't work in here. So how do I change route without a Link
Component
This is for a search bar
答案1
得分: 14
你应该导入导航 API 以推送/替换历史记录堆栈,以执行导航。
import { navigate } from 'gatsby'
以下是您可以在表单提交方法中使用它的方式。它类似于 React-Router 的 history.push()
。
submit() {
// 其余表单逻辑
navigate('/hello');
}
如果您希望替换历史记录堆栈,可以使用 navigate('/hello', { replace: true })
。您可以参考 Gatsby Link 文档 获取更多详细信息。
英文:
You should import the navigate API to push/replace the history stack, in order to carry out navigation.
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()
.
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.
答案2
得分: 3
你可以使用Gatsby的navigate
助手函数。
例如:
import React, { useState } from "react"
import { navigate } from "gatsby"
const Form = () => {
const [value, setValue] = useState("")
return (
<form
onSubmit={event => {
event.preventDefault()
navigate(`/${value}`)
}}
>
{/* 这里放入设置其值为状态的输入 */}
</form>
)
}
英文:
You can use Gatsby's navigate
helper function.
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>
)
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论