React Ref和 React forwardRef
Ref 和dom,Ref是reference(引用)的简写。
能力:
大多数情况下,props前递可以解决一切问题,但是依然有需要触达react实例或者Dom节点的情况,这时候应该使用React Ref。
使用:
用来处理立即执行的动画。
用来处理非受控组件的焦点。
用来与第三方库对接,我知道的有d3 或者 cocos。
React.forwardRef((props,ref)=><Compnent>)
简而言之就是自动透传引用(Ref),能让组件接收传过来的ref, 向下(或者说向前)传递Ref。
const FancyButton = React.forwardRef((props, ref) => (
<button ref={ref} className="FancyButton">
{props.children}
</button>
));
// You can now get a ref directly to the DOM button:
const ref = React.createRef();
<FancyButton ref={ref}>Click me!</FancyButton>;上述代码的解释:
首先创建了一个ref, 这个ref的目的就是抓到孙子组件中的input节点
通过组件属性把ref传给子组件<FancyButton>
子组件通过React.forwardRef透传props和ref,这里ref才是我们要注意的点。
参数ref赋值给孙子组件<button>
这个ref就能抓到孙子组件的实例。
React.forwardRef((props, ref)=><Componnet>)在高阶组件中的使用:
比如我们写一个打印前后属性的高阶组件logProps,这个高阶组件能够透传ref
function logProps(Component) {
class LogProps extends React.Component {
componentDidUpdate(prevProps) {
console.log('old props:', prevProps);
console.log('new props:', this.props);
}
render() {
const {forwardedRef, ...rest} = this.props;
// 把常规属性"forwardedRef"作为ref赋值给传过来的Component组件
return <Component ref={forwardedRef} {...rest} />;
}
}
// 注意React.forwardRef提供的第二个参数ref.
// 我们可以把ref作为一个常规属性"forwardedRef"传给LogProps这个组件
// 就可以跟实例绑定.
return React.forwardRef((props, ref) => {
return <LogProps {...props} forwardedRef={ref} />;
});
}本文内容仅供个人学习、研究或参考使用,不构成任何形式的决策建议、专业指导或法律依据。未经授权,禁止任何单位或个人以商业售卖、虚假宣传、侵权传播等非学习研究目的使用本文内容。如需分享或转载,请保留原文来源信息,不得篡改、删减内容或侵犯相关权益。感谢您的理解与支持!