React中ref的使用方法
在react典型的数据流中,
props
传递是父子组件交互的唯一方式;通过传递一个新的
props
值来使子组件重新
re-render
,从而达到父子组件通信。当然,就像react官网所描述的一样,在react典型的数据量之外,某些情况下(例如和第三方的dom库整合,或者某个dom元素focus等)为了修改子组件我们可能需要另一种方式,这就是
ref
方式。
1.ref有两种使用方法:
1)回调函数
标签中:
<input type="text" className="form-control" ref={ref => this.name = ref}/>
使用:
let name=this.name.value;
2)字符串
标签中:
<input type="text" className="form-control" ref="name"/>
使用:
let name=this.refs.name.value;
2.三种触发回调函数的时机:
1)组件被渲染后
2)组件被卸载后
3)ref改变后
3.注:
使用ref必须用在【类型式的组件】才起作用,用在【函数式的组件】是无效的。
更多专业前端知识,请上 【猿2048】www.mk2048.com