[英]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 ”结尾
我目前正在文件中的其他地方执行逻辑以检查搜索栏是否在特定页面上。 有了这个 boolean 值 ( isShoppingPage
),我想在用户点击 enter 时选择 append 一个 'type=shop' 到 url 以便它自动只搜索商店类别。 我尝试将“type=shop”附加到输入值,但 url 最终具有 URL 编码。 我对如何在不更改输入当前拥有和需要的name="q"
的情况下有条件地添加它感到困惑。
您可以使用form
的onSubmit
道具代替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>
)
};
这是来自 React 文档的指南
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.