【发布时间】:2022-01-12 07:58:53
【问题描述】:
我有一个搜索页面,something/search?q=foo,每当我在这个页面上我想把foo 放在我表单的值标签中。 (不用于搜索目的,我有一个功能齐全的搜索栏,我只是想向客户展示他搜索的最后一件事)。
我得到了搜索词:(window.location.href.indexOf("?q") != -1) ? window.location.href.substring(window.location.href.indexOf("?q") + 3) : '',这很有效,尽管当将其放入表单值标签时,立即反应块,它不允许我在输入字段中写入任何内容。我认为这是因为它更新到这个字符串的速度非常快,而你看不到它发生。
我将如何实现这一点,一次更新表单的值,仅此而已?
这是我的简化代码:
<input type="search" name="q" id="q" value={(window.location.href.indexOf("?q") != -1) ? window.location.href.substring(window.location.href.indexOf("?q") + 3) : ''} <--- This is where I want to put the search string
到目前为止我尝试过的是:
this.state = {
value:''
}
...
handleTitle = (s) => {
this.setState({value:s})
}
...
<input ... value={this.state.value} onChange={this.HandleTitle((window.location.href.indexOf("?q") != -1) ? window.location.href.substring(window.location.href.indexOf("?q") + 3) : '')}
这会导致无限状态更新
【问题讨论】:
-
您是否在您的应用程序中使用过任何类型的路由器?路由器可以轻松提供该查询。
-
获取搜索词不是问题,问题是如何将其放入值字段
-
请更新您的问题。向我们展示代码你是怎么做的?我会说为值字段设置一个状态。使用 useEffect 并设置查询词。并将该输入作为输入字段的值。
-
我试过这个,但它给了我无限的状态更新和应用程序崩溃
标签: javascript reactjs forms virtual-dom