【发布时间】:2021-06-06 20:58:34
【问题描述】:
情境化
我正在使用 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>
);
};
基本上,每次用户键入并调用函数SearchOptions.searchOn(event.currentTarget.value) 时都会调用函数handleChange。 searchOn 将返回没有键和正确链接的输入值。例如,如果用户输入“!y炸土豆”,返回将是{link: "https://www.youtube.com/results?search_query=fried potato", search: "fried potato"}。表单提交时,actionproper 路径正确,但内容仍然是“!y炸土豆”,这是真正输入的值。
同样,问题是:有什么方法可以在提交之前更改表单值?。我尝试将输入的值保存在一个状态中,并将这个状态传递给隐藏输入中的道具value,但这不起作用。我真的不知道提交功能是如何工作的。
【问题讨论】:
标签: html reactjs typescript forms submit