Call child method from parent

前端 未结 16 2116
长发绾君心
长发绾君心 2020-11-21 22:23

I have two components.

  1. Parent component
  2. Child component

I was trying to call child\'s method from Parent, I tried this way but couldn\

16条回答
  •  不思量自难忘°
    2020-11-21 23:27

    Here's a bug? to look out for: I concur with rossipedia's solution using forwardRef, useRef, useImperativeHandle

    There's some misinformation online that says refs can only be created from React Class components, but you can indeed use Function Components if you use the aforementioned hooks above. A note, the hooks only worked for me after I changed the file to not use withRouter() when exporting the component. I.e. a change from

    export default withRouter(TableConfig);
    

    to instead be

    export default TableConfig;
    

    In hindsight the withRouter() is not needed for such a component anyway, but usually it doesn't hurt anything having it in. My use case is that I created a component to create a Table to handle the viewing and editing of config values, and I wanted to be able to tell this Child component to reset it's state values whenever the Parent form's Reset button was hit. UseRef() wouldn't properly get the ref or ref.current (kept on getting null) until I removed withRouter() from the file containing my child component TableConfig

提交回复
热议问题