如何通过 i18next 从 hoc 翻译的组件中检索 ref

luk*_*z-p 4 javascript i18next reactjs react-i18next

我使用 i18next 在单独的 repo 中翻译我的组件。现在我需要使用主项目中一个组件的方法。这是示例组件:

class ExampleComponent extends React.Component {
  constructor(props) {
    this.state = {
      text: '',
    };
    this.resetText = this.resetText.bind(this);
  }

  resetText() {
    this.setState({
    text: '',
    });
  }

  render() {
    <div/>
  }

export default translate('components', { withRef: true })(ExampleComponent);
Run Code Online (Sandbox Code Playgroud)

现在我需要在我的主项目中使用 resetText,没有翻译它工作正常

class MainComponent extends Component {

  resetComponent() {
    return () => this.exampleComponent.resetText();
  }

  renderExampleComponent() {
    return (
      <ExampleComponent
        ref={(exampleComponent) => { this.exampleComponent = exampleComponent; }}
      />
    );
  }

  render() {
    return (
      <div>
        {this.resetComponent()}
      </div>
    );
  }
Run Code Online (Sandbox Code Playgroud)

我试过 this.refs.exampleComponent.resetText(); 但它不起作用。在 i18next 文档中,我发现“withRef | 存储对包装组件的引用并通过decoratedComponent.getWrappedInstance() 访问它;” 但是我应该在哪里使用这个 getWrappedInstance() 来使它工作?有人有这方面的经验吗?

你好

Gle*_*ost 5

我认为使用提供的代码,您的 ref 返回一个包装器,因此您需要对其调用 getWrappedInstance : this.refs.exampleComponent.getWrappedInstance().resetText();