以前你在父组件中使用<component ref="component"/>
的时候,你可以直接通过this.refs.component
进行获取。但是因为这里的component经过HOC的封装,已经是HOC里面的那个component了,所以你无法获取你想要的那个ref(wrappedComponent的ref)
。
要解决这个问题,这里有两个方法:
a) 像React Redux的connect方法一样,在里面添加一个参数,比如withRef
,组件中检查到这个flag了,就给下级组件添加一个ref,并通过getWrappedInstance方法获取。
function HOCFactory(wrappedComponent) {
return class HOC extends React.Component {
getWrappedInstance = ()=>{
if(this.props.widthRef) {
return this.wrappedInstance;
}
}
setWrappedInstance = (ref)=>{
this.wrappedInstance = ref;
}
render(){
let props = {
...this.props
};
if(this.props.withRef) {
props.ref = this.setWrappedInstance;
}
return <wrappedComponent {...props} />
}
}
}
export default HOCFactory(MyComponent);
class ParentCompoent extends React.Component {
doSomethingWithMyComponent(){
let instance = this.refs.child.getWrappedInstance();
// ....
}
render(){
return <MyComponent ref="child" withRef />
}
}
b) 还有一种方法,在官网中有提到过: 父级通过传递一个方法,来获取ref,具体看栗子:
先看父级组件:
class ParentCompoent extends React.Component {
getInstance = (ref)=>{
this.wrappedInstance = ref;
}
render(){
return <MyComponent getInstance={this.getInstance} />
}
}
复制代码
HOC里面把getInstance方法当作ref的方法传入就好
function HOCFactory(wrappedComponent) {
return class HOC extends React.Component {
render(){
let props = {
...this.props
};
if(typeof this.props.getInstance === "function") {
props.ref = this.props.getInstance;
}
return <wrappedComponent {...props} />
}
}
}
export default HOCFactory(MyComponent);
Component上面绑定的Static方法会丢失
// 定义一个static方法
WrappedComponent.staticMethod = function() {/*...*/}
// 利用HOC包裹
const EnhancedComponent = enhance(WrappedComponent);
// 返回的方法无法获取到staticMethod
typeof EnhancedComponent.staticMethod === 'undefined' // true