如何在HOC中使用refs反应?

时间:2018-10-12 08:55:14

标签: reactjs ref higher-order-components

我有一个组件(包装有HOC),该组件已安装在我的应用程序中的多个位置。我必须在<a [navigator]="url" [navigator.condition]="myCondition">My link</a> 中使用SELECT CA.MEMBER_ID, 0 AS TRANSFERRED_SHARES , SUM(CA.NUMBER_OF_SHARES) AS PURCHASED_SHARES, '-' AS DELETED_SHARES FROM COS_APPLICATIONS CA , COS_APPL_DETAILS CAD WHERE APPL_TYPE =2 AND CA.APPLICATION_ID = CAD.APPLICATION_ID AND CA.SERVICE_PRODUCT = 38002 AND CAD.TRX_TYPE = 'INITIAL' AND CAD.TRX_UNIT = 143 GROUP BY CA.MEMBER_ID UNION ALL SELECT CA.MEMBER_ID, SUM(CA.NUMBER_OF_SHARES) AS TRANSFERRED_SHARES, 0 AS PURCHASED_SHARES , '-' AS DELETED_SHARES FROM COS_APPLICATIONS CA , COS_APPL_DETAILS CAD WHERE APPL_TYPE =5 AND CA.APPLICATION_ID = CAD.APPLICATION_ID AND CA.SERVICE_PRODUCT = 38002 AND CAD.TRX_TYPE = 'INITIAL' AND CAD.TRX_UNIT = 143 GROUP BY CA.MEMBER_ID ORDER BY CA.MEMBER_ID 添加一些自定义事件,例如dragdragLeave等,并且需要在node.addEventListener中将其删除。我尝试将ref提供给HOC(在其中安装WrapperComponent的位置),但是它给我一个错误,ComponentDidMount不是函数,因为它给了我该组件的实例,但不是该HOC的DOM节点。如何使用ComponentWillUnmount解决此问题?

这是我的HOC的样子:

node.addEventListener

编辑 我不想在这里使用refs

1 个答案:

答案 0 :(得分:1)

向WrappedComponent添加一个引用,然后找到DOM实例

export default function Connector() {
    return function wrap(WrappedComponent) {
        class MyComponent extends PureComponent {
            componentDidMount(){
                //find node here and attach event listener
                this.node = ReactDOM.findDOMNode(this.componentRef);

            }
            componentWillUnmount(){
                //remove event listener
            }

            ....
            render() {
               <WrappedComponent 
                   {...this.props}
                   ref={(ref) => this.componentRef = ref}
               />
            }
        }
    }
}

另一种方法是将propinnerRef传递给WrappedComponent,然后将其留给包装的组件,以将ref传递给DOM节点

   <WrappedComponent 
        {...this.props}
        innerRef={(ref) => this.componentRef = ref}
   />

然后在WrappedComponent中

 render() {
     return (
        <div ref={this.props.innerRef}>{/* */}</div>
     )
  }