Skip to main content

Refs引用

前言

Refs 提供了一种方式,允许我们访问 DOM 节点或在 render 方法中创建的 React 元素

创建 Refs

class MyComponent extends React.Component {
constructor(props) {
super(props);
this.myRef = React.createRef();
}
render() {
return <div ref={this.myRef} />;
}
}
export default MyComponent

访问 Refs

const node = this.myRef.current;

注意:你不能在函数组件上使用 ref 属性,因为他们没有实例。