我正在嘗試使用帶有輸入和按鈕的 React 的代碼。當我單擊一個按鈕時,我想清除輸入,否則情況并非如此。這是我的代碼:
import { useState } from "react";
import "./styles.css";
const App = () => {
const [finalValue, setFinalValue] = useState(true);
const changevalue = () => {
setFinalValue(!finalValue);
};
return (
<div className="App">
{finalValue ? (
<input
type="text"
placeholder=" E-mail"
className="mt-1 block w-full border-none bg-gray-100 h-11 rounded-xl shadow-lg hover:bg-blue-100 focus:bg-blue-100 focus:ring-0"
/>
) : (
<input
type="text"
placeholder=" Pseudo"
className="mt-1 block w-full border-none bg-gray-100 h-11 rounded-xl shadow-lg hover:bg-blue-100 focus:bg-blue-100 focus:ring-0"
/>
)}
<button onClick={() => changevalue()}>Change input</button>
</div>
);
};
export default App;
這是我的代碼:https ://codesandbox.io/s/wandering-fire-hj8d84?file=/src/App.js:0-823
請問你能幫幫我嗎 ?
非常感謝 !
注意:我嘗試使用value但無法在輸入中輸入,我也嘗試使用defaultValue但沒有任何成功。
uj5u.com熱心網友回復:
你必須使用useRef我在下面實作了這個,
首先,您必須匯入useRefHook 然后制作一個常量one
const one = useRef("")然后在input標簽中添加ref={one}.
然后在changevalue函式中你必須寫one.current.value = "";
import { useState ,useRef } from "react";
import "./styles.css";
const App = () => {
const [finalValue, setFinalValue] = useState(true);
const one = useRef("");
const changevalue = () => {
setFinalValue(!finalValue);
one.current.value = "";
};
return (
<div className="App">
{finalValue ? (
<input ref={one}
type="text"
placeholder=" E-mail"
className="mt-1 block w-full border-none bg-gray-100 h-11 rounded-xl shadow-lg hover:bg-blue-100 focus:bg-blue-100 focus:ring-0"
/>
) : (
<input type="text" ref={one}
placeholder=" Pseudo"
className="mt-1 block w-full border-none bg-gray-100 h-11 rounded-xl shadow-lg hover:bg-blue-100 focus:bg-blue-100 focus:ring-0"
/>
)}
<button onClick={changevalue}>Change input</button>
</div>
);
};
export default App;
uj5u.com熱心網友回復:
首先,您可以const [inputValue, setInputValue] = useState('');使用/更改/清除輸入值;然后只需將 value 和 onChange 函式設定為輸入標簽(event.target.value 將是您的輸入字串值)。使用您的按鈕,只需將 inputValue 設定為默認 ''; 希望這有幫助
uj5u.com熱心網友回復:
試試這個
import { useState, useRef } from "react";
import "./styles.css";
const App = () => {
const [finalValue, setFinalValue] = useState(true);
const emailRef = useRef();
const changevalue = () => {
setFinalValue(!finalValue);
emailRef.current.value = "";
};
return (
<div className="App">
{finalValue ? (
<input
type="text"
ref={emailRef}
placeholder=" E-mail"
className="mt-1 block w-full border-none bg-gray-100 h-11 rounded-xl shadow-lg hover:bg-blue-100 focus:bg-blue-100 focus:ring-0"
/>
) : (
<input
type="text"
ref={emailRef}
placeholder=" Pseudo"
className="mt-1 block w-full border-none bg-gray-100 h-11 rounded-xl shadow-lg hover:bg-blue-100 focus:bg-blue-100 focus:ring-0"
/>
)}
<button onClick={() => changevalue()}>Change input</button>
</div>
);
};
export default App;
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/524929.html
上一篇:如何創建切換狀態的按鈕?
