使用React.createRef创建引用而不在React中使用构造函数?

时间:2019-01-18 16:18:08

标签: javascript reactjs ref

基本上,我出于3个原因在constructor中使用了React-

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吗?

5 个答案:

答案 0 :(得分:5)

您可以像state一样将其声明为类字段。

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

Babel会将其转换为类似于下面的Stage-2预设中的代码。

constructor(props) {
    super(props);

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

答案 1 :(得分:3)

类组件上,如下所示:

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

答案 2 :(得分:1)

是的。与您对国家所做的完全一样(在Babel的类字段支持下):

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

答案 3 :(得分:1)

您可以使用引用回调创建引用,而无需使用构造函数。 <input ref={(element) => { this.inputRef = element; }} />是您所需要的。

答案 4 :(得分:1)

是的,可以。例如:

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

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

唯一无法做的就是将ref属性传递给功能组件:

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

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

  

但是,只要引用DOM元素或类组件,就可以在函数组件内使用ref属性: