【问题标题】:Can't access forwareded Ref value in parent component React typescript无法访问父组件 React 打字稿中的转发 Ref 值
【发布时间】:2021-09-22 17:56:50
【问题描述】:

我有一种情况,我创建了一个输入组件。这是一个自定义组件,我想访问用户在父组件(我正在使用它的地方)的此输入中输入的值。

我正在从这个输入组件转发 ref,但父组件接收的是完整的输入而不是值。我如何使用该值。 下面是我的代码。

输入.tsx

  interface AuxProps {
      id :''
    }

const Input = React.forwardRef<HTMLInputElement,AuxProps>((props, ref) => {
  return (      
      <input 
      id={props.id}   
      ref = {ref}         
      defaultValue = '1' 
      type='number' 
      ></input>
  );
});
export default Input;

HeaderComponent.tsx

const HeaderComponent= () => {

  const inputAmount = useRef<HTMLInputElement>(null);
  const addProductHandle = (event: any) => {
    event.preventDefault();
    console.log(inputAmount.current.value);     //<----Error:- object is possibly null
  };
  return (
    <form className={classes["form"]}>
      <Input id="1s" ref={inputAmount}></Input>
      <button onClick={addProductHandle}> + ADD </button>
    </form>
  );
};
export default HeaderComponent;

不知道如何使用这个 ref 值。

【问题讨论】:

    标签: reactjs typescript react-redux components ref


    【解决方案1】:

    你很亲密。

    我们来看看useRef返回类型:

      interface RefObject<T> {
            readonly current: T | null;
        }
    

    根据这种类型签名,current 属性可能是T(在我们的例子中是HTMLInputElement)或null

    这就是您使用 typescript 的原因 - 以避免在 PROD 上出现错误。

    由于current 可能是null,TS 要求您仔细检查current 是否存在。

    您可以添加?if condition

    import React, { useRef, MouseEventHandler } from 'react'
    
    interface AuxProps {
        id: string
    }
    
    const Input = React.forwardRef<HTMLInputElement, AuxProps>((props, ref) => {
        return (
            <input
                id={props.id}
                ref={ref}
                defaultValue='1'
                type='number'
            ></input>
        );
    });
    
    
    const HeaderComponent = () => {
    
        const inputAmount = useRef<HTMLInputElement>(null);
        const addProductHandle: MouseEventHandler<HTMLButtonElement> = (event) => {
    
            event.preventDefault();
            console.log(inputAmount.current?.value);     // ok 
            if (inputAmount.current) {
                console.log(inputAmount.current.value); //ok
            }
        };
        return (
            <form >
                <Input id="1s" ref={inputAmount}></Input>
                <button onClick={addProductHandle}> + ADD </button>
            </form>
        );
    };
    export default HeaderComponent;
    

    顺便说一句,您可以将MouseEventHandler&lt;HTMLButtonElement&gt; 用于点击处理程序。看我的例子

    【讨论】:

    • 行得通!感谢您的详细解释。
    猜你喜欢
    • 2022-11-17
    • 1970-01-01
    • 2018-10-09
    • 2021-12-27
    • 2020-10-30
    • 2020-02-16
    • 2020-11-27
    • 2020-10-15
    • 1970-01-01
    相关资源
    最近更新 更多