'this' keyword is undefined inside Mapping Statement (React)

眉间皱痕 提交于 2020-02-16 10:44:08

问题


The this keyword inside the vidsAsHtml mapping function keeps returning undefined.

I read this, and a couple other SO questions about this but their solutions did not solve the problem. I'm already using es6 syntax arrow function for the map, but I've also tried putting in this as a second argument, which didn't solve the issue. Curious if anyone knows why 'this' keyword keeps coming up as undefined here.

 import React, { useState, useEffect } from 'react'
    import axios from 'axios'

    const VideoGrid = (props) => {
      const [videos, setResource] = useState([])

      const fetchVideos = async (amount, category) => {
        const response = await axios.get('https://pixabay.com/api/videos/', {
          params: {
            key: '123456679',
            per_page: amount,
            category: category
          }
        })

        console.log(response)
        const vidsAsHtml = response.data.hits.map(vid => {
          return (
            <div className={`${props.page}--grid-content-wrapper`} key={vid.picture_id}>
              <div className={`${props.page}--grid-video`}>
                <video
                  poster="https://i.imgur.com/Us5ckqm.jpg"
                  onMouseOver={this.play()}
                  onMouseOut={this.pause()}
                  src={`${vid.videos.tiny.url}#t=1`} >
                </video>
              </div>
              <div className={`${props.page}--grid-avatar-placeholder`}></div>
              <div className={`${props.page}--grid-title`}>{vid.tags}</div>
              <div className={`${props.page}--grid-author`}>{vid.user}</div>
              <div className={`${props.page}--grid-views`}>{vid.views} 
                <span className={`${props.page}--grid-date`}> • 6 days ago</span>
              </div>
            </div>
          )
      })
      setResource(vidsAsHtml)
    }

      useEffect(() => {
        fetchVideos(50, 'people')
      }, []) 

        return (
          <main className={`${props.page}--grid-background`}>
            <nav className={`${props.page}--grid-nav`}>

              <button 
                id='followButton' 
                className={`${props.page}--grid-nav-${props.titleOne}`} 
                >{props.titleOne}
              </button>

              <button 
                id='recommendedButton' 
                className={`${props.page}--grid-nav-${props.titleTwo}`} 
                >{props.titleTwo}
              </button>

              <button 
                id='subscriptionsButton' 
                className={`${props.page}--grid-nav-${props.titleThree}`} 
                >{props.titleThree}
              </button>

              <button className={`${props.page}--grid-nav-${props.titleFour}`}>{props.titleFour}</button>
              <button className={`${props.page}--grid-nav-${props.titleFive}`}>{props.titleFive}</button>
              <button className={`${props.page}--grid-nav-follow`}>FOLLOW</button>
            </nav>
            <hr className={`${props.page}--grid-hr-nav-grey`} />
            <hr className={`${props.page}--grid-hr-nav-black`} />        

            <div className={`${props.page}--grid`} style={{marginTop: 'unset'}}>
              {videos}
            </div>
          </main>
        )
      }


    export default VideoGrid

回答1:


Event handler props are expected to be passed a function. Currently you are trying to pass the return values of this.play() and this.pause() as event handlers, which wouldn't work anyway.

Also React doesn't make the element available to the event handler via this, but you can access it via event.target:

<video
  poster="https://i.imgur.com/Us5ckqm.jpg"
  onMouseOver={event => event.target.play()}
  onMouseOut={event => event.target.pause()}
  src={`${vid.videos.tiny.url}#t=1`} >
</video>



回答2:


You can use ref for this,

let vidRef = React.createRef();

You should create function separately,

const playVideo = () => {
   // You can use the play method as normal on your video ref
    vidRef.current.play();
};

const pauseVideo = () => {
   // Pause as well
   vidRef.current.pause();
};

provide ref to video,

<video
  ref = {vidRef}   //Provide ref here
  poster="https://i.imgur.com/Us5ckqm.jpg"
  onMouseOver={() => playVideo()}
  onMouseOut={() => pauseVideo()}
  src={`${vid.videos.tiny.url}#t=1`} >
</video>

Demo



来源:https://stackoverflow.com/questions/59208424/this-keyword-is-undefined-inside-mapping-statement-react

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!