react 之 ref

react提供一个refs的安全口,做到‘接触’或调用 从render()返回的组件实例的方法、DOM节点。

用法:1. ref Callback属性

   ref 属性可以是一个回调函数,此函数会在这个组件被挂载后立即执行,此回调函数的参数就是当前这个组件或DOM节点,回调函数体内可以立即使用这个组件,或保存供以后使用;

 1 render(){
 2 return(
 3     <Textinput  ref={(c)=>{
 4         if(c != null)c.focus();          // 立即使用
 5     }}/>)
 6 };
 7 ==================
 8 render(){
 9 return(<input ref={(c)=>this._c = c}/>)     //保存
10 }
11 componentDidMount(){
12 this._c.focus();                                          //调用
13 }

  注:当被引用的组件卸载和每当ref变动,旧的ref将会被以null做参数调用。这阻止了在实例被保存的情况下的内存泄露。

用法2:ref String属性

  ref 同样支持使用字符串的形式作为一个组件的ref prop:

  <input ref="myInput"/> 访问用 this.refs.myInput.value 或 this.refs['myInput'](此方法为保留Google Closure Compiler advanced-mode crushing resilience)。

注:1.决不再组件的render()方法中访问refs。

  2.refs不能连接到一个stateless fuanction,因为无状态组件不支持组件实例,没有生命周期。