首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >React:无法为我的可重用输入组件使用forwardRef获取ref的值

React:无法为我的可重用输入组件使用forwardRef获取ref的值
EN

Stack Overflow用户
提问于 2021-05-10 15:37:13
回答 1查看 1.2K关注 0票数 0

我创建了登录页面的页面,我使用可重用的输入组件来处理页面所需的所有输入框。我想使用useRef来选择密码输入框,这样我就可以创建一个函数,在用户单击眼睛图标时将密码显示到文本中。但是,当我想获得密码输入框的值时,我遇到了一个未定义的问题。

每次单击眼睛图标时返回的值都是未定义的。

login.js

代码语言:javascript
复制
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

代码语言:javascript
复制
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}
      />
    </>
  )
);
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-05-10 15:40:24

正如文档所述,参考文献将在第二个论点中提供如下所示:

代码语言:javascript
复制
const FancyButton = React.forwardRef((props, ref) => (  
  <button ref={ref} className="FancyButton">    
    {props.children}
  </button>
));

来自https://reactjs.org/docs/forwarding-refs.html

所以你的输入应该是这样的:

代码语言:javascript
复制
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}
      />
    </>
  )
);
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/67473462

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档