转发Refs
- React.forwardRef 用来获取传递给它的ref。
- React.createRef()创建一个ref。
/**
* Created by mapbar_front on 2019/8/2.
*/
import React,{Component} from 'react';
function handleClick(ref){
console.log('ref',ref.current);
}
const FancyButton = React.forwardRef((props,ref)=>(
<button ref={ref} {...props} onClick={ ()=>handleClick(ref) }>
{props.children}
</button>
));
class Refs extends Component{
constructor(props){
super(props);
this.ref = React.createRef();
}
handleClick= (ref)=>{
alert(1);
}
render(){
return(
<div>
<FancyButton
ref={this.ref}
//onClick={ ()=>this.handleClick(this.ref)}
>
点我
</FancyButton>
</div>
)
}
}
export default Refs;
对于上面的例子逐步的说明:
- 我们调用React.createRef创建一个ReactRef并将其分配给ref变量。
- 然后把ref变量传给
- 在FancyButton中通过React.forwardRef接受ref。
- 在button上就可以得到ref,比如上面的点击事件。
注意:
- 第二个ref参数仅在使用React.forwardRef调用定义的组件时才存在,常规的类组件和函数组件不接受ref,而且props也不接受ref。
- Ref转发不限于DOM,您也可以转发给类组件实例。