【问题标题】:React property not appearing as query parameter反应属性未显示为查询参数
【发布时间】:2016-06-13 23:38:57
【问题描述】:

我有一个小表单,用于通过 URL 传递一个值(作为查询参数)。表格如下:

<form method="GET">
    <input type="hidden" value={`${this.props.age}`} name="p" />
    <a href="profile" class="btn btn-primary" type="submit">View</a>   
</form>

这个想法是从新页面中的 URL 访问年龄值。比如:

http://localhost:8000/?age=13

但是,当我单击链接时,URL 中没有出现任何查询参数。有人知道如何解决这个问题吗?提前致谢!!

【问题讨论】:

    标签: javascript html reactjs


    【解决方案1】:

    我认为您应该使用&lt;button&gt; 而不是&lt;a&gt;。因为当您单击View 时,您会转到/profile/ 页面(href 具有属性/profile/)但不会将表单提交到服务器。 buttonatype 属性含义不同

    按钮 - type 属性指定按钮的类型。

    a - type 属性指定链接文档的 Internet 媒体类型(以前称为 MIME 类型)。

    <form method="GET">
      <input type="hidden" value={`${this.props.age}`} name="p" />
      <button className="btn btn-primary" type="submit">View</button>
    </form>
    

    Example


    您也可以触发submit 方法,并阻止&lt;a&gt; 的默认操作

    var App = React.createClass({
      submit: function (e) {
        e.preventDefault();
        this.refs.form.submit();
      },
      
      render: function() {
        return <form method="GET" ref="form">
          <input type="hidden" value={`${this.props.age}`} name="p" />
          <a href="profile" class="btn btn-primary" onClick={ this.submit }>View</a>   
        </form>;
      }
    });
    

    Example

    【讨论】:

      【解决方案2】:

      &lt;a&gt; 标记不会提交您的表单,只会重定向到不同的 url。

      以下应该有效:

      <form method="GET" action="profile">
          <input type="hidden" value={this.props.age} name="p" />
          <button class="btn btn-primary" type="submit">View</button>   
      </form>
      

      【讨论】:

        【解决方案3】:

        &lt;a&gt; 标记仅重定向到页面。 然后,您可能需要添加一些 css 代码,使按钮看起来像 &lt;a&gt; 标记。

        <form method="GET" action="profile">
        <input type="hidden" value={this.props.age} name="p" />
        <button class="btn btn-primary" type="submit">View</button>   
        </form>
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2015-12-11
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多