0

мне нужно обратиться к элементу и навесить на него обработчик событий, не понимаю как это сделать...

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

2
  • вы можете повесить событие с помощью свойства onClick
    – azlov
    5 авг 2020 в 13:51
  • можно поставить <a-video ref={setup}, где function setup(element){... 5 авг 2020 в 20:59

1 ответ 1

0

Используйте 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>

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.