我在 React 中為一個簡單的任務而苦苦掙扎我有一個接受字串或數字的輸入欄位。按下重置按鈕時,輸入欄位的值應該變為空白,以便我可以添加一個新字串。我已經可以清除表單,但是當它被清除時,我無法輸入其他內容。是因為我正在使用狀態嗎?有什么解決辦法嗎?
我的代碼:
import React from 'react';
import './Input.css';
import { useState } from 'react';
const Input = () => {
const [value, setValue] = useState();
const SearchButton = (e) => {
e.preventDefault();
console.log("click");
};
const ResetButton = (e) => {
e.preventDefault();
setValue(" ");
};
return (
<main>
<form className='inputfield'>
<h2 className='input-text'>Zoek een Github user</h2>
<div className='input'>
<input className='search' type='text' placeholder='Typ hier een gebruikersnaam...' value={value}></input>
<div className='button-field'>
<button className='search-now' onClick={SearchButton}>Zoeken</button>
<button className='reset' onClick={ResetButton}>Reset</button>
</div>
</div>
</form>
</main>
);
};
export default Input;
uj5u.com熱心網友回復:
您的輸入中應該有一個onChange函式。
<input onChange={(e) => setValue(e.target.value)}></input>
檔案
uj5u.com熱心網友回復:
更改值時忘記更新狀態。例如:
<input
className='search'
type='text'
placeholder='Typ hier een gebruikersnaam...'
value={value}
onChange={e => setValue(e.target.value)}
></input>
基本上發生的事情是,當您的組件第一次加載時,您沒有使用狀態,因此input“不受控制”,因為valueis undefined. 然后“重置”為狀態設定一個值,因此input現在使用該值。但它需要一種方法來改變這個值。
順便說一句,我還建議使用空字串作為初始狀態,而不是undefined:
const [value, setValue] = useState("");
這樣,即使它是空的,值也至少是 something 。您可能還希望“重置”使用空字串而不是空格:
setValue("");
因為空格是非空值,它會導致占位符文本不再顯示。所以它并不是真正“重置”輸入,它只是將其更改為空白值。
uj5u.com熱心網友回復:
enprimer lugar, debe cambiar el valor setValue y debería verse así
const [value, setValue] = useState('');
其次,您需要將其添加到輸入中
<input onChange={(e) => setValue(e.target.value)}></input>
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/444598.html
