2017-07-19 32 views
1

我正在使用lifecycle來創建高階組件。我需要訪問封裝的組件實例。我怎麼才能得到它?如何用重構獲取包裝組件實例?

例如

export default function ajaxLoader(options) { 
    return lifecycle({ 
     componentWillMount() { 
      // how to get *wrapped* component instance here? 
      // `this` refers to an instance of the lifecycle HOC, not the wrapped component 
      // i.e., I want the instance of `SomeComponent` 
     } 
    }) // this returns a function that accepts a component *class* 
} 

和使用,如果你想看到它:

class SomeComponent extends React.PureComponent { 

    render() { 
     return <span/>; 
    } 
} 

const WrappedComponent = ajaxLoader({ 
    // options 
})(SomeComponent); 

認爲我本來可以對包裝組件的引用,如果我在HOC推翻了render()方法,並使用ref=...呈現包裹組件,但recompose明確不會讓我自己實現render方法。

它支持整個組件API,除了使()方法,它是通過缺省實現(和如果指定重寫;一個錯誤將被記錄到控制檯)。

+0

你不能在'生命週期'中獲取被包裝的組件。你想要做什麼與包裝組件?我不明白你的使用例子。 – wuct

+0

@wuct示例並不是要演示一個用例,只是結構。假設我想在包裝的實例上調用一個自定義方法,我該怎麼做? – mpen

+1

無法訪問'生命週期'中的包裝組件或實例。您可能應該將這些方法提升到更高階的組件,或者只使用普通的React.Component。 – wuct

回答

2

如果你必須可以訪問實例方法,你可以做這樣的事情:

class ParentComponent extends Component { 
    constructor(props) { 
    super(props); 
    this.childController = null; 
    } 

    // access child method via this.childController.instanceMethod 

    render() { 
    return <DecoratedChildComponent provideController={controller => this.childController = controller} /> 
    } 
} 

class ChildComponent extends Component { 
    componentDidMount() { 
    this.props.provideController({ 
     instanceMethod: this.instanceMethod, 
    }) 
    } 

    componentWillUnmount() { 
    this.props.provideController(null); 
    } 

    instanceMethod =() => { 
    console.log("I'm the instance method"); 
    } 
} 

這是一個有點令人費解,而且在大多數情況下是可以避免的,但你真的需要訪問實例方法,這將工作