类组件中:
创建Refs
Refs 是使用 React.createRef()
创建的,并通过 ref
属性附加到 React 元素。在构造组件时,通常将 Refs 分配给实例属性,以便可以在整个组件中引用它们。
class MyComponent extends React.Component {
constructor(props) {
super(props);
this.myRef = React.createRef();
}
render() {
return <div ref={this.myRef} />;
}
}
访问 Refs
当 ref 被传递给 render
中的元素时,对该节点的引用可以在 ref 的 current
属性中被访问。
const node = this.myRef.current;
函数组件中:
创建Refs
在函数组件中使用时,应该创建一个refs
const loginformRef = React.createRef();
注意:一定要在定义组件之前进行创建,否则获取不到current!
使用Refs
对需要使用的对象进行绑定!
访问Refs
可以通过loginformRef.current的方法进行使用。打印出current看看!