如何在 Gatsby 中更改路由而不使用 Link 组件?

huangapple go评论82阅读模式
英文:

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 &lt;/Link&gt;(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 &#39;gatsby&#39;

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(&#39;/hello&#39;);
}

If you wish to replace the history stack, you may use navigate(&#39;/hello&#39;, { 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 &quot;react&quot;
import { navigate } from &quot;gatsby&quot;

const Form = () =&gt; {
  const [value, setValue] = useState(&quot;&quot;)

  return (
    &lt;form
      onSubmit={event =&gt; {
        event.preventDefault()
        navigate(`/${value}`)
      }}
    &gt;
      {/* here goes your input that sets its value to state with `setValue` */}
    &lt;/form&gt;
  )
}

huangapple
  • 本文由 发表于 2020年1月7日 00:31:54
  • 转载请务必保留本文链接:https://go.coder-hub.com/59615674.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定