我创建了登录页面的页面,我使用可重用的输入组件来处理页面所需的所有输入框。我想使用useRef来选择密码输入框,这样我就可以创建一个函数,在用户单击眼睛图标时将密码显示到文本中。但是,当我想获得密码输入框的值时,我遇到了一个未定义的问题。
每次单击眼睛图标时返回的值都是未定义的。
login.js
const Login = ({ history }) => {
const textRef = useRef();
const showRefContent = () => {
console.log(textRef);
};
return (
<FormContainer>
<form
noValidate
onSubmit={handleSubmit}
className='w-10/12 h-2/4 mx-auto flex flex-col justify-center'
>
<div className='form-group w-full relative'>
<InputField
type='password'
placeholder='Password'
name='password'
ref={textRef}
value={userInfo.password}
onChange={handleChange}
/>
<FontAwesomeIcon
icon={faEye}
className='absolute top-4 right-4 opacity-60'
onClick={showRefContent}
/>
</div>
</form>
</FormContainer>
);
};inputField.js
import React, { forwardRef } from 'react';
const InputField = forwardRef(
({ value, label, name, placeholder, type, onChange, ref }) => (
<>
{label && <label htmlFor='input-field'>{label}</label>}
<input
type={type}
value={value}
name={name}
className='bg-customBlack-light hover:bg-customBlackLighter-light w-full text-xs p-4 mb-6 rounded-md outline-none transition duration-150 ease-in-out'
placeholder={placeholder}
onChange={onChange}
ref={ref}
/>
</>
)
);发布于 2021-05-10 15:40:24
正如文档所述,参考文献将在第二个论点中提供如下所示:
const FancyButton = React.forwardRef((props, ref) => (
<button ref={ref} className="FancyButton">
{props.children}
</button>
));来自https://reactjs.org/docs/forwarding-refs.html
所以你的输入应该是这样的:
import React, { forwardRef } from 'react';
const InputField = forwardRef(
({ value, label, name, placeholder, type, onChange }, ref) => (
<>
{label && <label htmlFor='input-field'>{label}</label>}
<input
type={type}
value={value}
name={name}
className='bg-customBlack-light hover:bg-customBlackLighter-light w-full text-xs p-4 mb-6 rounded-md outline-none transition duration-150 ease-in-out'
placeholder={placeholder}
onChange={onChange}
ref={ref}
/>
</>
)
);https://stackoverflow.com/questions/67473462
复制相似问题