如何解决如何过滤将在表单中提交的内容
情境化
我正在与 ReactJS 合作创建一个小表单,该表单根据用户类型重定向到新站点(例如谷歌)。它是这样工作的:如果用户输入“!y炸土豆”,代码必须重定向到显示所有“炸土豆”视频的youtube搜索页面,但如果用户在输入中只输入“炸土豆”,代码必须用“炸土豆”的所有结果打开谷歌。换句话说,程序必须识别文本中是否有“键”并打开不同的选项卡。
好的。侦听输入并设置正确站点的逻辑代码正在运行,但我的想法是:如何过滤将发送到提交表单的内容?因为当用户直接输入“!y炸土豆”时,youtube页面上的搜索内容将是“!y炸土豆”而不仅仅是“炸土豆”(没有键)。有什么办法可以在发送表单内容之前删除密钥?
上面的代码是处理这个功能的组件:
export const SearchInput: React.FC = () => {
//searchPath => state containing the correct path to the site
//value => state containing the inputted value
//form => form reference to call the submitted method
const [searchPath,setSearchPath] = React.useState<string>();
const [value,setValue] = React.useState<string>("")
const form = React.createRef<HTMLFormElement>();
//handle whit the input
const handleChange = (event: React.ChangeEvent<HTMLInputElement>) => {
// SearchOptions.searchOn() handle with the input and return the searched content and the path
// search => constant containing the input value without the key
// link => const containing the correct path to the site
const { search,link } = SearchOptions.searchOn(event.currentTarget.value);
setSearchPath(link);
setValue(search);
};
// Call the submit method
const handleSubmit = (event: any) => {
event.preventDefault();
event.stopPropagation();
form.current?.submit();
};
return (
<form
ref={form}
className="input-container"
method="get"
onSubmit={handleSubmit}
action={searchPath ?? "http://google.com.br/search"}
>
<input type="hidden" name="sitesearch" value="" />
<input
type="search"
name="q"
className="search-input"
placeholder="Search on Google"
onChange={handleChange}
/>
<button id="search" name="confirm" type="submit" onClick={handleSubmit}>
Search
</button>
</form>
);
};
基本上,每次用户键入并调用函数 handleChange
时都会调用函数 SearchOptions.searchOn(event.currentTarget.value)
。 searchOn
将返回没有键和正确链接的输入值。例如,如果用户输入“!y 炸土豆”,则返回{link: "https://www.youtube.com/results?search_query=fried potato",search: "fried potato"}
。提交表单时,道具action
有正确的路径,但内容仍然是“!y 炸土豆”,一旦它是真正的输入值。
再次,问题是:有什么方法可以在提交之前更改表单值?。我尝试将输入的值保存在一个状态中,并将这个状态传递给隐藏输入中的道具 value
,但这不起作用。我真的不知道提交功能是如何工作的。
解决方法
通常,您根本不会依赖原生 HTML 表单的 submit
行为。 event.preventDefault()
的目的就是为了做到这一点。相反,只需直接在处理程序中执行您想要的任何逻辑。例如
import { useState } from 'react'
const Search = () => {
const [inputValue,setInputValue] = useState('')
const handleChange = (event) => {
setInputValue(event.target.value)
}
const handleSubmit = (event) => {
event.preventDefault()
const [type,searchTerm] = inputValue.split(/\s+/,2)
const encoded = encodeURIComponent(searchTerm)
if (type === '!y') {
window.location = `https://www.youtube.com/results?search_query=${encoded}`
} else if (type === '!g') {
window.location = `http://www.google.com/search?q=${encoded}`
} // ... etc
}
return (
<form onSubmit={handleSubmit}>
<input value={inputValue} onChange={handleChange} />
<button type="submit">Search</button>
</form>
)
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。