跳至內容

react/no-string-refs 正確性

此規則預設為開啟。

此規則的作用

此規則禁止在 ref 屬性中使用字串文字。

範例

此規則的錯誤程式碼範例

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

var Hello = createReactClass({
  componentDidMount: function () {
    var component = this.refs.hello;
    // ...do something with component
  },
  render: function () {
    return <div ref="hello">Hello, world.</div>;
  },
});

此規則的正確程式碼範例

jsx
var Hello = createReactClass({
  componentDidMount: function () {
    var component = this.hello;
    // ...do something with component
  },
  render() {
    return (
      <div
        ref={(c) => {
          this.hello = c;
        }}
      >
        Hello, world.
      </div>
    );
  },
});

參考資料

以 MIT 授權釋出。