React Router v4 <Link>表格 [英] React Router v4 <Link> for Form

查看:41
本文介绍了React Router v4 <Link>表格的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何将

一起使用?我正在尝试避免程序化路由,因为我看到很多针对它的警告.

How can I use <Link> with a <form>? I am trying to avoid programatic routing as I see many warnings against it.

表单有两个字段:

<form>
    <input type="text" id="what"/>
    <input type="text" id="where"/>
    <Link><button type="submit"></Link>
</form>

我的目标是将页面发送到 '/' + document.getElementById('where').value + '/' + document.getElementById('what').value,是吗可以使用 v4 路由器吗?

My goal is to send the page to '/' + document.getElementById('where').value + '/' + document.getElementById('what').value, is it possible with v4 router?

推荐答案

在 v4 中, 仅用于创建 元素.

With v4, the <Link> is only used to create <a> elements.

我认为大多数针对程序化导航的警告来自于人们并没有真正理解 history 是如何工作的,尤其是在尝试在组件之外进行时.withRouter HOC 提供了一种向组件添加路由的简单方法.

I think that most warnings against programmatic navigation come from people not really understanding how history works, especially when attempting to do it outside of components. The withRouter HOC provides an easy way to add routing to a component.

此外,我会从表单组件内而不是从按钮进行路由.然后,您只需要确保按钮的类型是 submit(这是默认的).

Additionally, I would do the routing from within a form component instead of from the button. Then, you just need to make sure that the button's type is submit (which is the default).

您还使用 DOM 函数来访问代码中的值.我建议改为使用受控输入,但这显然取决于您.

You are also using DOM functions to access the values in your code. I would recommend instead using controlled inputs, but that is obviously up to you.

class NavForm extends React.Component {
  constructor(props) {
    super(props)
    this.state = {
      what: '',
      where: ''
    }

    this.submitHandler = this.submitHandler.bind(this)
    this.handleInput = this.handleInput.bind(this)
  }

  handleInput(event) {
    const target = event.target
    this.setState({
      [target.name]: target.value
    })
  }  

  submitHandler(event) {
    event.preventDefault()
    // do some sort of verification here if you need to
    this.props.push(`${this.state.where}/${this.state.what}`)
  }

  render() {
    return (
      <form onSubmit={this.submitHandler}>
        <input
          type='text'
          name='what'
          value={this.state.what}
          onChange={this.handleInput} />
        <input
          type='text'
          name='where'
          value={this.state.where}
          onChange={this.handleInput} />
        <button>Submit</button>
      </form>
    )
  }
}

export default withRouter(NavForm)

这篇关于React Router v4 &lt;Link&gt;表格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆