使用React.createRef创建Ref而不在React中使用构造函数? [英] Create Ref using React.createRef without using constructor in React?

查看:655
本文介绍了使用React.createRef创建Ref而不在React中使用构造函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

基本上,我在 React 中使用构造函数只有3个原因 -

Basically, I have used constructor in React for only 3 reasons -

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

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

but due to Babel's class-field support, I don't use it anymore

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



2。要 bind 函数,如 -



2. To bind functions like -

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

    increment() {

    }
}

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

but due to arrow functions, I don't do it anymore

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

    }
}



3。要使用 createRef 喜欢 -



3. To use createRef like -

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

我可以使用 React .createRef 在React中没有使用构造函数

So can I use React.createRef without using constructor in React?

推荐答案

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

You can declare it as an class field just like state.

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

Babel会将其转换为类似下面第2阶段预设代码的内容。

Babel will transpile it into something like the code below in stage-2 presets.

constructor(props) {
    super(props);

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

这篇关于使用React.createRef创建Ref而不在React中使用构造函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆