Skip to content
← Back to rules

react/no-string-refs Correctness

它的作用

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

为什么这很糟糕?

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

字符串 ref 已在 React 19 中被完全移除, 因此如果使用的是 React 19+,可以禁用此规则。

示例

以下是此规则的错误代码示例:

jsx
var Hello = createReactClass({
  render: function () {
    return <div ref="hello">你好,世界。</div>;
  },
});

var Hello = createReactClass({
  componentDidMount: function () {
    var component = this.refs.hello;
    // ...对 component 做一些处理
  },
  render: function () {
    return <div ref="hello">你好,世界。</div>;
  },
});

以下是此规则的正确代码示例:

jsx
var Hello = createReactClass({
  componentDidMount: function () {
    var component = this.hello;
    // ...对 component 做一些处理
  },
  render() {
    return (
      <div
        ref={(c) => {
          this.hello = c;
        }}
      >
        你好,世界。
      </div>
    );
  },
});

配置

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

noTemplateLiterals

type: boolean

default: false

除字符串字面量外,也不允许使用模板字面量。

如何使用

To enable this rule using the config file or in the CLI, you can use:

json
{
  "plugins": ["react"],
  "rules": {
    "react/no-string-refs": "error"
  }
}
ts
import { defineConfig } from "oxlint";

export default defineConfig({
  plugins: ["react"],
  rules: {
    "react/no-string-refs": "error",
  },
});
bash
oxlint --deny react/no-string-refs --react-plugin

版本

此规则在 v0.0.15 中添加。

参考资料