在我用 injectIntl​​ 包装它后丢失react组件参考

IT技术 javascript reactjs
2021-05-06 21:12:00

在我用injectIntl​​ 包装它之后,我在获取React 组件中func 的引用时遇到了问题。基本上我需要的是通过 ref 访问组件中的 func 这就是我正在做的

class MainContainer extends React.Component {
    constructor(props) {
        super(props);
        }

    getSamples(){
      return sth
    }

   render() {
        return (<div>this.props.sth</div>)
        }

export default injectIntl(MainContainer )

用injectIntl​​ 包裹后是否可以得到MainContainer 的引用?

2个回答

应该传递 withRef 选项。

export default injectIntl(MainContainer,{ withRef: true })

可以使用以下方法检索 MainContainer 包装器组件实例

<MainContainer ref={c => { this.container = c; }} />

可以使用以下方法检索包装的组件实例

this.container.getWrappedInstance();

injectIntl有一个forwardRef属性,导致它向下传递 ref 到被包装的组件。

// MyComponent.jsx
// ...
export default injectIntl(MyComponent, {forwardRef: true});
// MyApp.js
import MyComponent from 'MyComponent';
class MyApp {
  render() {
    this.myComponentRef = React.createRef();
    return <MyComponent ref={ref} />;
  }
} 

参考