React: “this” is undefined inside a component function

前端 未结 10 2117
春和景丽
春和景丽 2020-11-22 04:59
class PlayerControls extends React.Component {
  constructor(props) {
    super(props)

    this.state = {
      loopActive: false,
      shuffleActive: false,
    }         


        
10条回答
  •  情歌与酒
    2020-11-22 05:39

    In my case, for a stateless component that received the ref with forwardRef, I had to do what it is said here https://itnext.io/reusing-the-ref-from-forwardref-with-react-hooks-4ce9df693dd

    From this (onClick doesn't have access to the equivalent of 'this')

    const Com = forwardRef((props, ref) => {
      return  {console.log(ref.current} } />
    })
    

    To this (it works)

    const useCombinedRefs = (...refs) => {
      const targetRef = React.useRef()
    
      useEffect(() => {
        refs.forEach(ref => {
          if (!ref) return
    
          if (typeof ref === 'function') ref(targetRef.current)
          else ref.current = targetRef.current
        })
      }, [refs])
    
      return targetRef
    }
    
    const Com = forwardRef((props, ref) => {
      const innerRef = useRef()
      const combinedRef = useCombinedRefs(ref, innerRef)
    
      return  {console.log(combinedRef .current} } />
    })
    

提交回复
热议问题