在组件上定义 ref 时,如果使用 ESLint 进行代码检查,可能会出现警告。要消除这个警告,可以在定义 ref 的时候,使用箭头函数来绑定 this,例如:

<SomeComponent ref={node => this.myRef = node} />

这样就能消除 ESLint 的警告了。另外,如果需要在组件中使用 ref,可以在组件的构造函数中绑定 this,例如:

constructor(props) {
  super(props);
  this.myRef = null;
  this.setRef = element => {
    this.myRef = element;
  };
}

然后在组件中使用 ref 时,可以这样写:

<SomeComponent ref={this.setRef} />
如何消除 ESLint 在组件上定义 ref 时的警告

原文地址: https://www.cveoy.top/t/topic/ovml 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录