1 定义
实例
类中:
this.r1 = React.createRef();//实例一个ref , 包含current属性
渲染完以后可以用 this.xx.current 来获取dom
回调
类=>render=>定义并放入子组件=》
<Child ref={dom=>this.xx=dom}></Child>
在 componentDidMount 和componentDidUpdate 中
this.xx 就是dom
字符串绑定
<Child ref="xx"></Child>
this.refs.xx == dom
用的最多的是回调
转发:把子组件dom勾出来改
- 子组件要是个函数组件
函数组件
let Child2 = React.forwardRef((props,ref) => {
// console.log(ref);// this.r4 || el=>this.r4=el 回调函数本身
return (
<div>
<div ref={ref}>函数式组件</div>
</div>
)
});
render=>
<Child2 ref={el=>this.r4=el}></Child2>
父组件=》
componentDidMount(){
//抓取渲染后的dom元素,焦点控制,交给dom库,动画库
this.r4.style.background='yellow'
}
}
定义 <Child2 ref={this.inputRef}></Child2>
.