ts ref的使用
时间: 2024-02-28 22:52:18 浏览: 22
TypeScript中的`ref`是一个属性修饰符,用于获取组件或DOM元素的引用。它类似于React中的`ref`属性。
在TypeScript中使用`ref`,需要先在组件的属性列表中定义一个`ref`属性,类型为`React.RefObject`或者`React.MutableRefObject`。例如:
```typescript
import React, { useRef } from 'react';
interface MyComponentProps {
inputRef: React.RefObject<HTMLInputElement>;
}
const MyComponent: React.FC<MyComponentProps> = ({ inputRef }) => {
return (
<div>
<label htmlFor="my-input">Input:</label>
<input id="my-input" ref={inputRef} />
</div>
);
};
const App: React.FC = () => {
const inputRef = useRef<HTMLInputElement>(null);
const handleClick = () => {
if (inputRef.current) {
inputRef.current.focus();
}
};
return (
<div>
<MyComponent inputRef={inputRef} />
<button onClick={handleClick}>Focus Input</button>
</div>
);
};
```
在上面的例子中,我们定义了一个名为`inputRef`的`React.RefObject<HTMLInputElement>`类型的变量,然后将其传递给了`MyComponent`组件的`inputRef`属性。在`MyComponent`内部,我们将`inputRef`属性绑定到了`<input>`元素上的`ref`属性上,这样我们就可以在父组件中通过`inputRef.current`获取到该元素的引用并调用其方法,例如让其获取焦点。
值得注意的是,`React.MutableRefObject`与`React.RefObject`的区别在于,前者的`current`属性是可变的,而后者是只读的。通常情况下,我们使用`React.RefObject`就足够了。