React进阶笔记15(传递Refs)

这是将ref通过组件传递给其后代之一的技术。该技术对于高阶组件(也称为HOC)特别有用。

让我们从一个组件道具 记录到控制台的实例HOC开始。

function logProps(WrappedComponent){
    class LogProps extends React.Component{
        componentDidUpdate(prevProps){
            console.log('old props:',prevProps);
            console.log('new props:',this.props);
        }

        render(){
            return <WrappedComponent {...this.props} />
        }
    }

    return LogProps;
}

“logProps”HOC将传递props到它包装的组件,因此渲染的输出将是相同的。例如,我们可以使用此HOC记录传递给我们的“花式按钮”组件的所有道具:

class FancyButton extends React.Component{
    focus(){
        //...
    }
    //...
}

export default logProps(FancyButton);

上面的例子有一个警告:refs不会被传递。那是因为ref不是道具。比如key,它的处理方式与React不同。如果将引用添加到HOC,则引用将引用最外面的容器组件,而不是包装组件。

这意味着用于我们FancyButton组件的refs 实际上将附加到LogProps组件:

import FancyButton from './FancyButton';

const ref = React.createRef();

// The FancyButton component we imported is the LogProps HOC.
// Even though the rendered output will be the same,
// Our ref will point to LogProps instead of the inner FancyButton component!
// This means we can't call e.g. ref.current.focus()
<FancyButton
  label="Click Me"
  handleClick={handleClick}
  ref={ref}
/>;
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • 深入JSX date:20170412笔记原文其实JSX是React.createElement(componen...
    gaoer1938阅读 8,185评论 2 35
  • React进阶之高阶组件 前言 本文代码浅显易懂,思想深入实用。此属于react进阶用法,如果你还不了解react...
    流动码文阅读 1,232评论 0 1
  • refs提供了一种方法,用于访问在render中创建的dom节点或者React元素。 在典型的React数据流中,...
    XKolento阅读 1,479评论 0 3
  • It's a common pattern in React to wrap a component in an ...
    jplyue阅读 3,408评论 0 2
  • 自己最近的项目是基于react的,于是读了一遍react的文档,做了一些记录(除了REFERENCE部分还没开始读...
    潘逸飞阅读 3,741评论 1 10

友情链接更多精彩内容