单击按钮时如何清除输入



我正在尝试使用带有输入和按钮的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,但没有成功。

您必须使用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;

首先,您可以使用const [inputValue, setInputValue] = useState('');来使用/更改/清除输入值;然后只需将value和onChange函数设置到输入标记中(event.target.value将是您的输入字符串值(。使用按钮只需将inputValue设置为默认值";希望这能帮助

试试这个

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;

最新更新