正常获取函数组件DOM,因为函数组件没有实例current,所以要使用React.forwardRef来配合React.createRef解决:
import React from 'react'
const TargetComponent = React.forwardRef((props, ref) => (
<input type="text" ref={ref} />
))
export default class Comp extends React.Component {
constructor() {
super()
this.ref = React.createRef()
}
componentDidMount() {
this.ref.current.value = 'ref get input'
}
render() {
return <TargetComponent ref={this.ref} />
}
}
在typescript项目中类似上面的应用:
import React, { FC, useRef} from "react";
import Input from "../Input";
import { SelectProps } from "./SelectProps";
export const Select: FC<SelectProps> = (props) => {
const { defaultValue, placeholder, disabled, multiple, name, onChange, onVisibleChange, children } = props;
const input = useRef<HTMLInputElement>(null);
return (
<div className="select-input">
<Input
placeholder={placeholder}
name={name}
disabled={disabled}
value={value}
icon="angle-down"
readOnly
ref={input}
/>
</div>
);
};
如下报错:说Input组件上没有ref属性-属性不兼容:
解决如下:
function createRef<T>(): RefObject<T>;
创建ref:private inputRef = React.createRef<HTMLInputElement>();
function forwardRef<T, P = {}>(Component: RefForwardingComponent<T, P>): ForwardRefExoticComponent<PropsWithoutRef<P> & RefAttributes<T>>;
使用:
const FancyInput = React.forwardRef<HTMLInputElement, {}>((props, ref) => { return <input type="text" ref={ref} className="fancy-input" />; });
如下解决:
export const Input = React.forwardRef<HTMLInputElement, InputProps>((props, ref) => {
return (
<input className="input-inner" {...props} ref={ref} />
);
});
export const Input: FC<InputProps & { ref: React.Ref<HTMLInputElement> }> = React.forwardRef((props, ref) => {
return (
<input className="input-inner" {...props} ref={ref} />
);
});