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;
总结:
- inputRef.current!.focus() 这里的!为断言inputRef.current不为null
- 主要还是在ts中使用类型不熟练导致比较很多坑
如有错误的地方欢迎提出 😃