reactモーダルを開いた時、「<div className="js-slider" ref={ref => (this.canvas = ref)} />」をrenderして
querySelectorのようにthis.canvasを取得したいですが、componentDidMountやbutton clickイベント時に
console.log(`this.canvas: ${this.canvas}`);
を入れてもundefinedが出てしまいます。
import React, { Component } from 'react'; import styled from 'styled-components'; import Modal from 'styled-react-modal' import * as YouTubeIframeLoader from 'youtube-iframe'; import noUiSlider from 'nouislider'; let playClipYoutube = () => { console.log('this is playClipYoutube function'); const sliderWrap = document.querySelector('.js-slider'); console.log(`sliderWrap: ${sliderWrap}`); //null YouTubeIframeLoader.load(function(YT) { let player = null; if (player) { player.destroy(); } player = new YT.Player('player', { height: '390', width: '640', videoId: 'dm8IdS52pXI', events: { onReady: () => { player.playVideo(); } } }); }); } class MovieModal extends Component { constructor (props){ super(props) this.state = { isOpen: false, } this.toggleModal = this.toggleModal.bind(this) } toggleModal (e) { console.log(`toggleModal - this.canvas: ${this.canvas}`); this.setState({ isOpen: !this.state.isOpen }) console.log('e:',e); console.log("this.state.isOpen:",this.state.isOpen); if(this.state.isOpen === false){ playClipYoutube(); console.log(`this.canvas: ${this.canvas}`); //undefined } } componentDidMount() { console.log(`MovieModal componentDidMount this.canvas: ${this.canvas}`); } render() { return ( <div> <button onClick={this.toggleModal}>Click me</button> <StyledModal isOpen={this.state.isOpen} onBackgroundClick={this.toggleModal} onEscapeKeydown={this.toggleModal}> <div className="js-slider" ref={ref => (this.canvas = ref)} /> <button onClick={this.toggleModal}>Close me</button> </StyledModal> </div> ); }} export default MovieModal const StyledModal = Modal.styled` width: 60rem; height: 40rem; display: flex; align-items: center; justify-content: center; background-color: white; `
何か間違ったコードがありましたら教えていただけますでしょうか。

回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。