使用 React.createRef 时出错 - "You must pass either a valid element or a valid id"
Error whlie using React.createRef - "You must pass either a valid element or a valid id"
我有以下代码:
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.
怎么了?
如果您正在尝试做类似的事情; (https://jsfiddle.net/oLpz88mL/13/) 您可以在 fiddle 上查看此示例以获取知识库。
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);
据我所知,这样就可以了
const player = new Vimeo(this.videoRef.current)
此处您正在使用 React.createRef 创建一个 ref。它存储对 current
字段内元素的引用。
我有以下代码:
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.
怎么了?
如果您正在尝试做类似的事情; (https://jsfiddle.net/oLpz88mL/13/) 您可以在 fiddle 上查看此示例以获取知识库。 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);
据我所知,这样就可以了
const player = new Vimeo(this.videoRef.current)
此处您正在使用 React.createRef 创建一个 ref。它存储对 current
字段内元素的引用。