как подключить функцию к компоненту react?
мне нужно обратиться к элементу и навесить на него обработчик событий, не понимаю как это сделать...
import React, { Fragment } from 'react'
export default class Scenes_5_20 extends React.Component {
render() {
return (
<Fragment>
// элемент, к которому нужно обратиться
<a-video src="assets/video/approach.mp4" position="-0.5 0 -5" width="4" height="2"></a-video>
</Fragment>
)
}
}
// функция, которую нужно выполнить
var video = document.getElementById("video");
var pausing_function = function () {
if (this.currentTime >= 10) {
this.pause();
this.removeEventListener("timeupdate", pausing_function);
}
};
video.addEventListener("timeupdate", pausing_function);
Ответы (1 шт):
Автор решения: xydope
→ Ссылка
Используйте componentDidMount, см. пример ниже.
Заменил ваш компонент a-video на video для наглядности.
class Scenes_5_20 extends React.Component {
componentDidMount() {
const video = document.getElementById("video");
const pausing_function = ({target}) => {
if (target.currentTime > 10) {
target.pause();
video.removeEventListener("timeupdate", pausing_function);
}
console.log(target.currentTime)
};
video.addEventListener("timeupdate", pausing_function);
}
render() {
return ( <React.Fragment >
<video src = "https://file-examples-com.github.io/uploads/2017/04/file_example_MP4_480_1_5MG.mp4"
id = "video"
controls />
</React.Fragment>
)
}
}
ReactDOM.render( < Scenes_5_20 / > , document.getElementById('root'))
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id='root'></div>