使用react和Material和TypeScript,我无法为Material组件找到合适的类型T
。因此,我使用HTMLInputElement
作为RefObject T
参数,因为它还有一个focus
方法。
const focus = (inputRef: RefObject<HTMLInputElement>) => {
if (inputRef.current !== null) {
inputRef.current.focus()
}
}
在这种情况下,用什么替代HTMLInputElement
来正确地表示RefObject中的TextField
API?我希望资料-UI至少能导出类似"TextFieldRef“的东西,但情况似乎并非如此。
要明确的是,我在代码中的任何地方都没有使用HTMLInputElement
,使用它只是让TypeScript正常工作的一种方法,因为Material和HTMLInputElement
的TextField
都有一个focus
方法。
提前感谢!
发布于 2022-09-18 11:29:06
首先,这真的取决于你想要实现什么。您是要集中文本字段的输入还是根元素的输入?
来自MUI文档:
ref
被转发到根元素。
要获得对<input />
元素的引用,应该使用inputRef
支柱。在本例中,您应该使用你可以在这里读到。,因为它是幕后的输入。
让我们深入研究mui代码库:
TextField代码库确实显示了一个接收inputRef
支柱的InputComponent
。
如果您确实想让ref转到root元素,我们可以看到TextFieldRoot
组件是接收引用的根元素。第179行:
<TextFieldRoot
className={clsx(classes.root, className)}
disabled={disabled}
error={error}
fullWidth={fullWidth}
ref={ref}
required={required}
color={color}
variant={variant}
ownerState={ownerState}
{...other}
>
所以让我们来探索它从哪里来。我们可以看到它是一个样式为FormControl
的组件。从第33行:
const TextFieldRoot = styled(FormControl, {
name: 'MuiTextField',
slot: 'Root',
overridesResolver: (props, styles) => styles.root,
})({});
从FormControl代码中我们可以了解到,FormControlRoot
根接收引用作为支柱,第215行:
return (
<FormControlContext.Provider value={childContext}>
<FormControlRoot
as={component}
ownerState={ownerState}
className={clsx(classes.root, className)}
ref={ref}
{...other}
>
{children}
</FormControlRoot>
</FormControlContext.Provider>
);
});
最后,从第22行我们可以理解它只是一个样式的div..。
const FormControlRoot = styled('div', {
...
因此,现在,基于MUI基本代码,您可以根据需要在HTMLInputElement
和HTMLDivElement
之间进行选择。
https://stackoverflow.com/questions/73757845
复制相似问题