mirror of
https://github.com/NetEase/tango.git
synced 2026-07-03 12:24:26 +08:00
34 lines
840 B
Plaintext
34 lines
840 B
Plaintext
# 组件实例获取
|
||
|
||
TangoBoot 支持快捷设置和获取组件的实例。
|
||
|
||
## 借助 `withRef` 注册组件实例
|
||
|
||
`withRef` 是 TangoBoot 内置的实例注册 HOC,可以快捷的进行组件实例的注册和获取。基本的用法如下:
|
||
|
||
```tsx
|
||
class Input extends React.Component {
|
||
foo() {}
|
||
|
||
render() {
|
||
return <input {...this.props} />;
|
||
}
|
||
}
|
||
|
||
const ClassInput = withRef()(Input);
|
||
```
|
||
|
||
借助 `withRef` 包裹组件后,当新的组件实例被设置 `id` 属性时,会自动将对应的实例注册到 `tango.refs` 中。例如:
|
||
|
||
```tsx
|
||
export function Basic() {
|
||
const inputRef = useRef();
|
||
useEffect(() => {
|
||
console.log(tango.refs.classInput, inputRef.current);
|
||
}, []);
|
||
|
||
// 设置 id 属性后,会自动组件实例到 `tango.refs` 中
|
||
return <ClassInput id="classInput" ref={inputRef} />;
|
||
}
|
||
```
|