react使用forwardRef改造class类组件(TypeScript)

react的官网有js版的关于forwordRef改造类组件的示范这里不再过多赘述

假设有如下类组件


interface Props {
  value?: string;
  age?: number;
  onChange?: (value: string, e?: React.ChangeEvent<HTMLInputElement>) => void;
  inputRef:React.Ref<HTMLInputElement>

}
interface State {
  value?: string;
  name?: string;
}
class Input extends React.PureComponent<Props, State> {
  render() {
    const { inputRef } = this.props;
    return (
      <>
        <input type="text" ref={inputRef} />
      </>
    );
  }
}

export default Input

使用forwardRef改造后如下


function Input (): React.ForwardRefExoticComponent<IInputProps & React.RefAttributes<HTMLInputElement>>{
	class Input extends React.PureComponent<Props, State> {
	  render() {
	    const { inputRef } = this.props;
	    return (
	      <>
	        <input type="text" ref={inputRef} />
	      </>
	    );
  		}
	}
  return forwardRef(props:Props,ref:React.Ref<HTMLInputElement>) => {
      return <Input {..props} inputRef={ref}/>
    }
}

export default Input()

用法

function MyInput() {
  const inputRef = useRef<HTMLInputElement>(null);
  useEffect(() => {
    inputRef.current!.focus();
    console.log(inputRef.current!.value);
  }, []);
  return (
     <Input ref={inputRef} />
  );
}

export default MyInput;

总结:

  1. inputRef.current!.focus() 这里的!为断言inputRef.current不为null
  2. 主要还是在ts中使用类型不熟练导致比较很多坑

如有错误的地方欢迎提出 😃

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值