React学习笔记

React进阶笔记15(传递Refs)

2018-08-22  本文已影响0人  XKolento

这是将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}
/>;
上一篇 下一篇

猜你喜欢

热点阅读