【问题标题】:Create Ref using React.createRef without using constructor in React?使用 React.createRef 创建 Ref 而不是在 React 中使用构造函数?
【发布时间】:2019-06-12 22:36:34
【问题描述】:

基本上,我在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 吗?

【问题讨论】:

    标签: javascript reactjs ref


    【解决方案1】:

    类组件上写如下:

    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】:

      您可以将其声明为类字段,就像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();
        }
      

      【讨论】:

        【解决方案3】:

        是的,你可以。例如:

        const MyComponent = () => {
          const inputRef = React.createRef();
        
          return (
            <input ref={inputRef} />
          );
        }
        

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

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

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

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

        【讨论】:

          【解决方案4】:

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

          【讨论】:

            【解决方案5】:

            是的。就像你对状态所做的那样(使用 Babel 的类字段支持):

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

            【讨论】:

              猜你喜欢
              • 2017-07-24
              • 1970-01-01
              • 2013-09-24
              • 1970-01-01
              • 1970-01-01
              • 2021-12-25
              • 2013-05-06
              • 2018-03-24
              相关资源
              最近更新 更多