如何将上下文绑定到React功能组件

时间:2020-05-31 13:59:32

标签: reactjs react-functional-component

我有一个从子组件回调调用的函数。我正在尝试访问一些状态变量,但变量为undefined。我认为问题在于子组件回调函数上下文时,它未绑定到父组件。怎么做。

确保在调用myFunciton之前已设置myVariable。

const MyParentView = props => {

   const[myVariable, setMyVariable] = useState(undefined)

   const onTextFieldChange = val => {
       setMyVariable(val)
   }

   const myFunction = () => {
       // myVariable is set to some value by this time
       console.log(myVariable)
       // But it logs undefined
   }

   return (
      <Input onChange={e => onTextFieldChange(e.target.value)}
      <MyChildComponent getData={()=>myFunction()}/>
   )
}

以下是子组件(实际的一个)

// @flow

import React, { useEffect, useRef } from "react"
import { get } from "lodash"

type Props = {
  children: any,
  getData?: Function,
  threshold?: number
}

const InfiniteScroll = ({ children, getData, threshold = 0.9 }: Props) => {
  const listRef = useRef()

  useEffect(() => {
    window.addEventListener("scroll", handleScroll)
    return () => window.removeEventListener("scroll", handleScroll)
  }, [])

  useEffect(() => {
    if (listRef.current) {
      const bottom = listRef.current.getBoundingClientRect().bottom
      const height =
        window.innerHeight || get(document, "documentElement.clientHeight")

      if (bottom <= height) {
        getData && getData()
      }
    }
  })

  const handleScroll = () => {
    const winScroll =
      get(document, "body.scrollTop") ||
      get(document, "documentElement.scrollTop")

    const height =
      get(document, "documentElement.scrollHeight") -
      get(document, "documentElement.clientHeight")

    const scrolled = winScroll / height
    if (scrolled >= threshold) {
      getData && getData()
    }
  }

  return <div ref={listRef}>{children}</div>
}

export default InfiniteScroll

1 个答案:

答案 0 :(得分:0)

尝试像这样在myFunction中返回闭包:

const myFunction = () => {
      return function() {
       // myVariable is set to some value by this time
       console.log(myVariable)
       // But it logs undefined
      }
   }