如何使用createRef()代替this.refs?

时间:2019-03-13 14:26:04

标签: reactjs dom undefined ref refs

我在一个使用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'

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

感谢您的帮助!

2 个答案:

答案 0 :(得分:2)

字符串常量和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>
    );
  }
}

答案 1 :(得分:0)

尝试一下:

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>
    );
  }
}