如何使用 recompose 获取包装好的组件实例?
How to get wrapped component instance with recompose?
我正在使用 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()
方法,我可以获得对包装组件的引用,并使用 [=14 渲染包装组件=],但是 recompose
特别不允许我自己实现 render
方法。
It supports the entire Component API, except the render() method, which is implemented by default (and overridden if specified; an error will be logged to the console).
如果您必须访问实例方法,您可以这样做:
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");
}
}
这有点复杂,在大多数情况下可以避免,但如果您确实需要访问实例方法,这会起作用
我正在使用 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()
方法,我可以获得对包装组件的引用,并使用 [=14 渲染包装组件=],但是 recompose
特别不允许我自己实现 render
方法。
It supports the entire Component API, except the render() method, which is implemented by default (and overridden if specified; an error will be logged to the console).
如果您必须访问实例方法,您可以这样做:
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");
}
}
这有点复杂,在大多数情况下可以避免,但如果您确实需要访问实例方法,这会起作用