[英]onChange event is not being triggered in react js
試圖使以下組件的 onChange 事件觸發,但它沒有。 當我在搜索框中鍵入時,控制台上沒有打印任何內容。 沒有更改被觸發
const Search = () => {
let history = useHistory()
const [search, setSearch] = useState('')
const handleSubmit = (e) => {
e.preventDefault()
if (search) {
console.log("typing..")
history.push(`/?search=${search}`)
} else {
history.push(history.push(history.location.pathname))
}
}
return (
<Form.Group controlId='searchbox' onSubmit={handleSubmit}>
<Form.Control
className="auth-input"
type='text'
placeholder="Search..."
onChange={(e) => setSearch(e.target.value)}
>
</Form.Control>
<Button type='submit'>Submit</Button>
</Form.Group>
)
}
export default Search
const Home =()=>{
return (<div><Search /><div>)
}
導出默認主頁我仍然無法確定錯誤在哪里。 我如何讓它工作?
我假設 Form.control 是自定義控件或第三方控件,因此您無法將其轉換為受控輸入。 您可以嘗試創建一個 ref 並從 ref 獲取值並使用本機 js 添加 onChange 事件處理程序。 如果自定義控件不是第三方控件,那么您可以在 Form.Control 組件中添加 onChange 處理程序,並將 function 引用傳遞給控件。
編輯:
這是您的解決方案:https://codesandbox.io/s/vigorous-mclean-4jusl?file=/src/App.js
如果您在沙盒中看到錯誤,請刷新頁面。 codeandbox 似乎有一些錯誤。
說明:
使用 useRef 創建一個 ref 以訪問輸入:
const controlref = useRef();
將 ref 傳遞給控件:
<Form.Control
onChange={handleChange}
**ref={controlref}**
type="text"
placeholder="search..."
/>
使用 ref 獲取 onChange 中的值:
const handleChange = (e) => {
console.log(controlref.current.value);
setSearch(controlref.current.value);
};
首先,html“輸入”是一個自閉合元件。
其次,您錯過了 Input 組件中的“值”。
你的代碼:
<Form.Control
className="auth-input"
type='text'
placeholder="Search..."
onChange={(e) => setSearch(e.target.value)}
></Form.Control>
解決方案:
<Form.Control
className="auth-input"
type='text'
placeholder="Search..."
onChange={(e) => setSearch(e.target.value)}
value={search}
/>
嘗試使用事件 onInput 代替:
<Form.Control
className="auth-input"
type='text'
placeholder="Search..."
onInput={(e) => setSearch(e.target.value)}
/>
我不敢相信我犯了這個愚蠢的錯誤。 問題是由於我省略了標簽並將提交按鈕放在 <Form.Group> 中,它沒有處理 onSubmit 事件的屬性。 所以我改變了這個
return (
<Form.Group controlId='searchbox' onSubmit={handleSubmit}>
<Form.Control
className="auth-input"
type='text'
placeholder="Search..."
onChange={(e) => setSearch(e.target.value)}
>
</Form.Control>
<Button type='submit'>Submit</Button>
</Form.Group>
)
它被修改為:
return (
<Form onSubmit={handleSubmit} >
<Form.Group controlId='searchbox' >
<Form.Control
className="auth-input"
type='text'
placeholder="Search..."
onChange={(e) => setSearch(e.target.value)}
>
</Form.Control>
<Button type='submit'>Submit</Button>
</Form.Group>
</Form>
)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.