我正在尝试遵循原子设计原则,但我不确定我是否做得正确。
我创建了三个组件:Form、ExpandableInput 和 Input。输入是 HTML 输入包装器,可扩展输入是带有下拉菜单的输入,而表单只是表单。我想从 Form 组件访问当前输入值,所以我正在做多个级别的 ref 转发。在 Form 组件中一切正常,但问题是我必须在 ExpandableInput 组件中使用 ref.current.value ,但出现以下错误。
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'.
我不知道如何告诉 typescript ExpandableInput 中的 ref 变量具有 Ref 类型并且不为空。我不知道多级转发ref是否是一种好习惯,也许有更好的方法来获取输入值。
示例代码:
添加表单
const Form = () => {
// Refs
const caRef = useRef<HTMLInputElement>(null);
return (
<FormTemplate >
<ExpandableInput
option={CompetenceAreaOption}
ref={caRef}
/>
</FormTemplate>
);
}
export default AddForm;
可扩展输入 const ExpandableInput = React.forwardRef<HTMLInputElement, IProps>((
props,
ref
): JSX.Element => {
const pickInputValue = (value: string): void => {
console.log(ref.current) // Error
console.log(ref) // Input reference
}
}
return (
<div>
<div>
<Input
ref={ref}
/>
</div>
</div>
);
})
export default ExpandableInput;
输入 const Input = React.forwardRef<HTMLInputElement, IProps>(({
props,
ref
): JSX.Element => {
return (
<input
ref={ref}
/>
);
})
export default Input;
最佳答案
ref
实际上有三个可能的值。已收到 forwardRef
.
type ForwardedRef<T> = ((instance: T | null) => void) | MutableRefObject<T | null> | null;
可以是null
.它可以是您所期望的,即 MutableRefObject
创建者 useRef
.第三种可能性是它可以是 callback function . (注意: string
不支持旧版 forwardRef
refs)。这三个中的任何一个都可以传递到下一个级别。但是如果我们想访问
ref.current
那么我们需要确保我们拥有的是一个 MutableRefObject
.我们使用类型保护器来做到这一点:if ( ref && "current" in ref)
.这样就可以访问 ref.current
.ref.current
可能是 null
(当 ref 尚未附加到 DOM 时)。所以我们还需要检查current
对 if
有效或使用可选的链接运算符 ?.
精简版:if ( ref && "current" in ref) {
ref.current?.focus();
}
长版:// make sure that ref is a MutableRefObject
if (ref && "current" in ref) {
// input has type HTMLInputElement | null
const input = ref.current;
// exlude null current value
if (input) {
// now we know that we have an input
input.focus();
}
}
Typescript Playground Link
关于javascript - 多级转发引用 [Typescript/React],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64241270/