我有一個搜索頁面,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) : '')}
這會導致無限的狀態更新
uj5u.com熱心網友回復:
我建議您在組件安裝時獲取 search-param 的值,并將其存盤在組件的本地狀態中。然后從狀態讀取/更新值。就像是:
const [search, setSearch] = useState("");
useEffect(() => {
setSearch(new URLSearchParams(new URL(window.location.href).search).get('q'));
}, []);
return (
<intput type="text" value={search} onChange={e => setSearch(e.target.value)} />
);
我沒有測驗過它,但你明白了它的要點。
uj5u.com熱心網友回復:
無論如何,如果你想訪問本q機。
作業示例
https://8zwht.csb.app/?q=test
import React from "react";
import "./styles.css";
class App extends React.Component {
state = {
value: ""
};
componentDidMount() {
const search = new URL(window.location).searchParams;
const term = search.get("q");
if (term)
this.setState({
value: term
});
}
handleChange = (e) => {
this.setState({
value: e.target.value
});
};
render() {
return (
<input
type="text"
onChange={this.handleChange}
value={this.state.value}
/>
);
}
}
export default App;
uj5u.com熱心網友回復:
如果您共享代碼或要點,提供更具體的答案會更容易
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/376004.html
標籤:javascript 反应 形式 虚拟世界
下一篇:PHPMYSQL表單多次提交
