質問をすることでしか得られない、回答やアドバイスがある。

15分調べてもわからないことは、質問しよう!

新規登録して質問してみよう
ただいま回答率
85.48%
React.js

Reactは、アプリケーションのインターフェースを構築するためのオープンソースJavaScriptライブラリです。

Q&A

解決済

1回答

4543閲覧

reactモーダル開いた時、refで値を取得する方法

Kimsehwa

総合スコア312

React.js

Reactは、アプリケーションのインターフェースを構築するためのオープンソースJavaScriptライブラリです。

0グッド

0クリップ

投稿2018/11/19 12:14

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

何か間違ったコードがありましたら教えていただけますでしょうか。

気になる質問をクリップする

クリップした質問は、後からいつでもMYページで確認できます。

またクリップした質問に回答があった際、通知やメールを受け取ることができます。

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

guest

回答1

0

ベストアンサー

こちらでどうでしょうか。
onAfterOpen={handleAfterOpenFunc}

handleAfterOpenFunc = () => { playClipYoutube(); console.log(`this.canvas: ${this.canvas}`); }

投稿2018/11/19 14:43

編集2018/11/19 14:44
退会済みユーザー

退会済みユーザー

総合スコア0

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

15分調べてもわからないことは
teratailで質問しよう!

ただいまの回答率
85.48%

質問をまとめることで
思考を整理して素早く解決

テンプレート機能で
簡単に質問をまとめる

質問する

関連した質問