首页 > 解决方案 > 如何将上下文绑定到 React 功能组件

问题描述

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

可以确定 myVariable 在调用 myFunciton 之前设置。

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

标签: reactjsreact-functional-component

解决方案


尝试像这样返回一个闭包myFunction

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

推荐阅读