簡體   English   中英

如何重構包裝組件實例?

[英]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()方法,並且使用ref=...渲染了包裝組件,我我可以獲得對包裝組件的ref=... ,但具體recompose不會讓我自己實現render方法。

它支持整個Component API,但render()方法除外,它默認實現( 如果指定則覆蓋;將錯誤記錄到控制台)。

如果您必須有權訪問實例方法,則可以執行以下操作:

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");
  }
}

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM