在不使用 React 中的构造函数的情况下使用 React.createRef 创建 Ref?

Create Ref using React.createRef without using constructor in React?

基本上,我在 React 中使用 constructor 只有三个原因 -

1。初始化 state 就像 -

class App extends React.Component {
    constructor(props) {
        super(props);
        this.state = { counter: 0 };
    }
}

但由于 Babel class-field 的支持,我不再使用它了

class App extends React.Component {
    state = { counter: 0 };
}

2。到 bind 功能,如 -

class App extends React.Component {
    constructor(props) {
        super(props);
        this.increment.bind(this);
    }

    increment() {

    }
}

但由于 arrow 功能,我不再这样做了

class App extends React.Component {
    increment = () => {

    }
}

3。使用 createRef 就像 -

class App extends React.Component {
    constructor(props) {
        super(props);
        this.inputRef = React.createRef();
    }
}

那么我可以在 React 中使用 React.createRef 而不使用 constructor 吗?

是的。与您对状态所做的完全一样(使用 Babel 的 class-field 支持):

class App extends React.Component {
    inputRef = React.createRef();
}

您可以将其声明为 class 字段,就像 state 一样。

class App extends React.Component {
  state = { counter: 0 };
  inputRef = React.createRef();
}

Babel 会将其转译为类似于以下第 2 阶段预设中的代码。

constructor(props) {
    super(props);

    this.state = { counter: 0 };
    this.inputRef = React.createRef();
  }

您可以在不使用构造函数的情况下使用 ref 回调创建 ref。 <input ref={(element) => { this.inputRef = element; }} /> 就是你所需要的。

是的,你可以。例如:

const MyComponent = () => {
  const inputRef = React.createRef();

  return (
    <input ref={inputRef} />
  );
}

你唯一不能做的,就是将ref属性传递给功能组件:

render() {
  // This won't work.
  return <MyFunctionalComponent ref={this.inputRef} />
}

来自官方文档的更多信息,here

You can, however, use the ref attribute inside a function component as long as you refer to a DOM element or a class component:

class组件上写如下:

import React, { Component, createRef } from 'react';

class App extends Component {
  inputRef = createRef();

  render() {
    return (
      <div ref={this.inputRef}~~~
    );
  }
}

功能组件上写如下:

import React, { useRef } from 'react';

const App = () => {
  const inputRef = useRef(null);

  return (
    <div ref={inputRef}~~~
  );
};

毫无疑问,引用的元素是可变对象,但它应该在组件的整个生命周期内持续存在。这不是我的意见,这句话是为了 ReactJS docs.