Skip to content
← Back to rules

react/no-string-refs 正确性

它做了什么

此规则防止在 ref 属性中使用已弃用的字符串字面量行为。

为什么这是不好的?

自 React 16.3.0 起,已在 ref 属性中弃用字符串字面量的使用。

字符串 ref 已在 React 19 中完全移除,因此在使用 React 19 及以上版本时,可禁用此规则。

示例

以下为该规则的 错误 代码示例:

jsx
var Hello = createReactClass({
  render: function () {
    return <div ref="hello">Hello, world.</div>;
  },
});

var Hello = createReactClass({
  componentDidMount: function () {
    var component = this.refs.hello;
    // ...对 component 执行某些操作
  },
  render: function () {
    return <div ref="hello">Hello, world.</div>;
  },
});

以下为该规则的 正确 代码示例:

jsx
var Hello = createReactClass({
  componentDidMount: function () {
    var component = this.hello;
    // ...对 component 执行某些操作
  },
  render() {
    return (
      <div
        ref={(c) => {
          this.hello = c;
        }}
      >
        Hello, world.
      </div>
    );
  },
});

配置

此规则接受一个配置对象,包含以下属性:

noTemplateLiterals

type: boolean

default: false

除了禁止字符串字面量外,也禁止模板字面量。

如何使用

要通过配置文件或 CLI 启用 此规则,可以使用:

json
{
  "plugins": ["react"],
  "rules": {
    "react/no-string-refs": "error"
  }
}
bash
oxlint --deny react/no-string-refs --react-plugin

参考资料