React取不到ref的对象

class music extends React.Component {
constructor(props){
  super(props);
  this.state = {
      isPlay : false
  }
}

componentDidMount(){
  console.log('DidMount');
  console.log(this.ref.musicBox);
}

render(){
  return (
  <div>
     <div className="record">
      <img src="./images/唱片.svg"/>
      </div>
      <div className='music'>
      <audio ref="musicBox" src="./music/Lost Stars.mp3" controls="controls" loop='loop'>
       Your browser does not support the audio element.
      </audio>
      </div>
  </div>
 )
 }
}

想要取到audio标签然后判断它是否播放。但是在componentDidMount(){}中console它时报错:

DidMount
Cannot read property 'musicBox' of undefined

其实昨天在另外一个JS里面也遇到这个问题了~但是因为另外一个ref是写在动态生成的标签里面的,百度到说动态生成的标签ref会取不到。
但是这里是为什么会取不到ref呢?就在一个组件内,componentDidMount的this也应该不需要重新绑定的。

阅读 9.9k
1 个回答
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题