跳到主要内容

组件实例获取

TangoBoot 支持快捷设置和获取组件的实例。

借助 withRef 注册组件实例

withRef 是 TangoBoot 内置的实例注册 HOC,可以快捷的进行组件实例的注册和获取。基本的用法如下:

class Input extends React.Component {
foo() {}

render() {
return <input {...this.props} />;
}
}

const ClassInput = withRef()(Input);

借助 withRef 包裹组件后,当新的组件实例被设置 id 属性时,会自动将对应的实例注册到 tango.refs 中。例如:

export function Basic() {
const inputRef = useRef();
useEffect(() => {
console.log(tango.refs.classInput, inputRef.current);
}, []);

// 设置 id 属性后,会自动组件实例到 `tango.refs` 中
return <ClassInput id="classInput" ref={inputRef} />;
}