美文网首页React学习笔记
React进阶笔记15(传递Refs)

React进阶笔记15(传递Refs)

作者: XKolento | 来源:发表于2018-08-22 16:38 被阅读0次

这是将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}
/>;

相关文章

  • React进阶笔记15(传递Refs)

    这是将ref通过组件传递给其后代之一的技术。该技术对于高阶组件(也称为HOC)特别有用。 让我们从一个组件道具 记...

  • react forward ref的使用

    React 引用传递 Forwarding Refs 引用传递(Ref forwading)是一种通过组件向子组件...

  • React进阶笔记3(Refs & DOM)

    refs提供了一种方法,用于访问在render中创建的dom节点或者React元素。 在典型的React数据流中,...

  • React-Native 中 refs 属性的使用方法

    Refs属性不能传递 因为并不是像 key一样,refs是一个伪属性,React 对它进行了特殊处理。如果你向一个...

  • React 进阶目录

    React进阶(附录一)构建工具改造过程记录 React进阶(一)React进阶更新计划浅谈React进阶(二)为...

  • Refs

    Refs提供了一种访问DOM节点或在render方法中创建的React元素的方法。 refs是React组件中非常...

  • 关于react中refs的使用

    在react中,可以使用refs来访问dom,或者在render中创建react对象。 使用refs的主要用途是 ...

  • React 'Refs'

    ref 有两种 ref 方式 ref = ''string" //string ref = {this.saveI...

  • React Refs

    终于看到最后一章了。你可以通过使用 this 来获取当前 React 组件,或使用 ref 来获取组件的引用,实例...

  • React refs

    在一些特殊情况下,直接操作组件实例的方法还是必要或者有利的。所以React提供了一个打破限制的办法,这就是refs...

网友评论

    本文标题:React进阶笔记15(传递Refs)

    本文链接:https://www.haomeiwen.com/subject/zasyiftx.html