使用React.createRef时出错-“您必须传递有效的元素或有效的ID”

时间:2019-07-04 14:49:10

标签: reactjs vimeo-api

我有以下代码:

import Vimeo from '@vimeo/player';

class MyComponent extends React.Component {

  constructor(props) {
    super(props);
    this.videoRef= React.createRef();
  }

  componentDidMount() {
    const player = new Vimeo(this.videoRef);
  }

  render() {
   return (
    <item><iframe ref={this.videoRef} /></item>
  )
 }
}

但是,我得到new Vimeo(this.videoRef)和错误

Unhandled Rejection (TypeError): You must pass either a valid element or a valid id.

怎么了?

2 个答案:

答案 0 :(得分:0)

如果您尝试执行与此类似的操作; (https://jsfiddle.net/oLpz88mL/13/),您可以在小提琴上查看此示例以获取知识库。 HTML     

<div id="ad-slot">
  <iframe width="100%" height="480" src="//fiddle.jshell.net/zx488o9u/9/show/light/" frameborder="0"></iframe>
</div>

JS

// Player 1
var player1 = document.getElementById('player1');
var doc = player1.ownerDocument;
var win = doc.defaultView || doc.parentWindow;

console.log(player1 instanceof win.HTMLElement);

// Player 2
var iframe = document.getElementById('ad-slot').childNodes[1];
var idocument = iframe.contentDocument || iframe.contentWindow.document;
var player2 = idocument.getElementById('player2');
var doc = player2.ownerDocument;
var win = doc.defaultView || doc.parentWindow;

console.log(player2 instanceof win.HTMLElement);

答案 1 :(得分:0)

据我所知,这可以完成工作

const player = new Vimeo(this.videoRef.current)

这里您正在使用React.createRef创建一个引用。它将对元素的引用存储在current字段中。