如何有条件地附加 url 参数以形成文本输入

How to conditionally append a url parameter to form text input

我有一个只有一个输入的表单,它是搜索查询 url -

 <form className={styles.searchInputContainer} role="search" action="/search">
          <label htmlFor={id} className={styles.searchLabel}>{constants.search}</label>
          <input id={id} className={styles.searchInput} type="search" name="q" placeholder="Search..." autocomplete="off" />
</form>

目前,当我按下回车键时,url 将以 '/search?q=whatever_the_input_is'

结尾

我目前正在文件的其他地方执行逻辑以检查搜索栏是否在特定页面上。使用此布尔值 (isShoppingPage),我想在用户按回车键时有选择地将 'type=shop' 附加到 url,以便它自动仅搜索商店类别。我尝试将 'type=shop' 附加到输入值,但 url 最终具有 URL 编码。我很困惑如何在不更改输入当前拥有和需要的 name="q" 的情况下有条件地添加它。

您可以使用 formonSubmit 属性代替 action

import React, {useState} from 'react';

const Form = (props) => {
  const {styles, id, constants} = props;
  const [qValue, setQValue] = useState("");

  const handleSubmit = (e) => {
    e.preventDefault();
    // here you can make API call with q=qValue and type=shop
  };

  return (
    <form className={styles.searchInputContainer} role="search" onSubmit={handleSubmit}>
      <label htmlFor={id} className={styles.searchLabel}>{constants.search}</label>
      <input id={id} className={styles.searchInput} type="search" name="q" placeholder="Search..." autocomplete="off" value={qValue} onChange={e => setQValue(e.target.value)} />
    </form>
  )

};

这是 guide 来自 React 文档