reactjs - 我无法在 typescript 中使用 useRef 钩子正确输入 ref
问题描述
我正在尝试将 ref 从父组件(EditableCell)传递给子组件(输入),并.current.focus
在单击父组件时使用其属性。
我正在使用forwardRef
打字稿的功能,但我无法正确输入
interface Props {
// Some props type
}
const CellEditable = (props: Props) => {
const [isEditing, setEditing] = useState<boolean>(false)
const inputRef = useRef<HTMLInputElement>(null)
const handleClick = () => setEditing(!isEditing)
const opts = {
ref: inputRef,
value: props.value,
onChange: props.onChange
}
return (
<div onClick={handleClick}>
{
isEditing
? <InputText {...opts} />
: <div>{props.value}</div>
}
</div>
)
}
interface Props {
// Some props type
}
type Ref = HTMLInputElement
const InputText = forwardRef((props: Props, ref: Ref) => {
useEffect(() => {
ref?.current?.focus()
})
return (
<input
type='text'
ref={ref}
value={props.value}
onChange={props.onChange}
/>
)
})
使用上面的代码,我收到以下错误:
Argument of type '(props: Props, ref: Ref) => JSX.Element' is not assignable to parameter of type 'ForwardRefRenderFunction<unknown, Props>'.
Types of parameters 'ref' and 'ref' are incompatible.
Type '((instance: unknown) => void) | MutableRefObject<unknown> | null' is not assignable to type 'HTMLInputElement'.
Type 'null' is not assignable to type 'HTMLInputElement'. TS2345
如果我forwardRed
用泛型键入,我会得到另一种错误:
const InputText = forwardRef<Ref, Props>((props, ref) => { ... }
Property 'current' does not exist on type '((instance: HTMLInputElement | null) => void) | MutableRefObject<HTMLInputElement | null>'.
Property 'current' does not exist on type '(instance: HTMLInputElement | null) => void'. TS2339
最后,输入 refany
没有错误。
我是 Typescript 的新手,我不明白上面提到的错误。
解决方案
查看以下沙箱:https ://codesandbox.io/s/aged-night-3pwjs 。
TypeScript 警告您,您的 ref 可能为 null,因此任何带有 if 的代码ref.current
都应该用 if 语句包装,这将确保它ref.current
存在。
推荐阅读
- r - 从 R 中指定距离内的第二个数据帧中识别点
- kotlin - Mockk:如何模拟保存对象时生成的对象 ID(答案 + vararg)
- redis - 如何在 Redis 中启用 ACL 功能
- python - 外部任务失败时气流外部任务传感器不会失败
- jsf - WebAppNotLoadedException : UIleaf 不可见
- python - 如何同时检测python中的多个按键?
- php - 如何在 Woocommerce 中为每个订单项目内爆一系列项目详细信息?
- html - 彼此下方的 HTML Div 内容
- mysql - sql查询中缺少关键字
- python - Python Pandas:如何将“resample”与“idxmin”一起使用?