如何在功能组件内的处理函数中传递/使用 refs?
import React, { useRef } from 'react';
function RegisterUser() {
const emailInput = useRef(null);
const passwordInput = useRef(null);
const handleClickRegister = () => {
RegisterPersonMutation(email, password, callbackValue => {
emailInput.current.value = ''; // <---------------------this guy
passwordInput.current.value = ''; // <------------------and his friend
});
};
return (
<div className="register-wrap">
<form>
<input type="text" ref={emailInput} />
<input type="password" ref={passwordInput} />
</form>
<button onClick={() => handleClickRegister()}>Register</button>
</div>
);
}
export default RegisterUser;
答案 0 :(得分:0)
我仍然想知道如何使用 useRef
在嵌套函数中创建和使用 refs...但在这种情况下,Frank 是对的,我应该使用 useState
。
我已经在我的真实组件中使用它,所以它是这样的:
function LoginPage() {
const [email, setEmail] = useState('');
const [password, setPassword] = useState('');
handleClick(foo, bar, callback => {
setEmail('');
setPassword('');
});
<input value={email} />
<input value={password} />
}