我想在輸入時檢查輸入,而不是異步按下鍵或按鈕。如果有人輸入超過 4 個字母,我想將變數值設定為 true。
我認為如果在用戶單擊輸入框外部后將值設定為 true (如果值為 4 個或更多字母)也可以,但我更喜歡前者
模擬代碼
var hasTypedMoreThan4Letters = false; //changes to true when more than 4 letters are typed in inp1
<input type="text" className="input1" id="inp1" onChange={onTypingMoreThan4Letters}/>
不確定它是否有幫助,但下面的模擬圖片

uj5u.com熱心網友回復:
您需要受控組件(受控輸入)。這是我使用鉤子的版本。您將獲得在count變數中輸入的符號數量。
import "./styles.css";
import { useState } from "react";
export default function App() {
const [count, setCount] = useState(0);
function handleInput(e) {
setInput(e.target.value);
setCount((prev) => prev 1);
}
const [input, setInput] = useState("");
return (
<div className="App">
<input value={input} onInput={handleInput} />
<p>{count}</p>
</div>
);
}
uj5u.com熱心網友回復:
你可能會做這樣的事情。這將檢查是否輸入了超過 4 個字母,如果 hasMore 為真,則顯示一條訊息。
import React from 'react';
export default function App() {
const [hasMore, setHasMore] = React.useState(false)
const [val, setVal] = React.useState("");
const hasTypedMoreThan4Letters = (e)=>{
setHasMore(e.target.value.length > 4)
setVal(e.target.value)
}
return (
<div className="App">
<input type="text" className="input1" id="inp1" value={val} onChange={hasTypedMoreThan4Letters}/>
{hasMore && (
<h1> has more than 4 letters</h1>
)}
</div>
);
}
uj5u.com熱心網友回復:
我看不出你應該為值的長度設定第二個狀態的理由。
function App() {
const [value, setValue] = useState('');
const hasTypedMoreThan4Letters = value.length > 4;
const handleChange = (event) => {
setValue(event.target.value);
}
return <input onChange={handleChange} value={value} />;
}
uj5u.com熱心網友回復:
你可以像這樣創建一個函式。
因此,我為輸入值和檢查超過 4 個字符創建了兩種狀態。
import { useState } from "react";
const MyComponent = () => {
const [val, setVal] = useState("");
const [greaterthanfour, setGreaterthanfour] = useState(false);
const handleChange = (e) => {
setVal(e.target.value);
if( val.length > 4) setGreaterthanfour(true);
}
return (
<div>
<input value={val} onChange={handleChange} />
{
greaterthanfour ?
( <div> You have entered MORE than 4 characters </div> )
:
(<div> You have entered LESS than 4 characters </div> )
}
</div>
)
}
export default MyComponent;
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/477634.html
標籤:javascript 反应
上一篇:如何將鍵值移動到物件內的新陣列中
