【问题标题】:How to use createRef() instead of this.refs?如何使用 createRef() 而不是 this.refs?
【发布时间】:2019-08-04 06:27:02
【问题描述】:

我从事一个项目,该项目使用来自 creativetim 的 "react-notification-alert"。在他们的文档中,他们显示example 以使用他们的警报。这基本上适用于 this.ref 但我知道它已被贬值,所以我尝试使用 createRef() 替换它,如下所示:

class App extends Component {
    constructor(props);
    this.notifRef = React.createRef();

    myFunc(){
        this.notifRef.current.notify.notificationAlert(options);
    }

  render() {
    return (
      <div>
          <NotificationAlert ref={this.notifRef} />
        <button onClick={() => this.myFunc()}>Hey</button>
      </div>
    );
  }
}

但问题是控制台显示给我

无法读取未定义的属性“notificationAlert”

我尝试了很多解决方案,并在堆栈上看到了很多答案,但我很难理解它是如何工作的。

感谢您的帮助!

【问题讨论】:

    标签: reactjs dom undefined ref refs


    【解决方案1】:

    字符串常量和 createRef 的主要区别在于 createRef 将数据存储在 current 字段中,因为字符串常量将其存储在 this.refs[stringConstant] 中。

    所以你的代码可能是:

    class App extends Component {
        constructor(props) {
          this.notifRef = React.createRef();
        }
        myFunc(){
            this.notifRef.current.notificationAlert(options);
        }
    
      render() {
        return (
          <div>
              <NotificationAlert ref={this.notifRef} />
            <button onClick={() => this.myFunc()}>Hey</button>
          </div>
        );
      }
    }

    【讨论】:

    • 很好,非常感谢 Nikita 的解释。现在它可以正常工作了!我现在明白了:)
    【解决方案2】:

    试试这个:

    class App extends Component {
      constructor(props){
         super();
         this.myFunc = this.myFunc.bind( this );
      }
    
      myFunc(){
         this.notifRef.current.notify.notificationAlert(options);
      }
    
      render() {
        return (
          <div>
            <NotificationAlert ref={ e=> this.notifRef = e } />
            <button onClick={ this.myFunc }>Hey</button>
          </div>
        );
      }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-11-06
      • 2021-05-20
      • 2021-08-09
      • 2019-11-12
      • 2015-05-12
      • 2017-10-07
      • 2021-05-08
      • 2018-09-21
      相关资源
      最近更新 更多