reactjs - 如何将上下文绑定到 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
解决方案
尝试像这样返回一个闭包myFunction
:
const myFunction = () => {
return function() {
// myVariable is set to some value by this time
console.log(myVariable)
// But it logs undefined
}
}
推荐阅读
- python - 在二叉树中递归返回一个布尔值?
- websocket - 信号器在 WebSocket 握手期间不使用 https 错误:意外的响应代码:200
- python - django restframework 如何计算对象并获取自(时间戳)?
- postgresql - 对 Postgresql 进行少量写入时经过的时间变化很大
- oracle-apex - Oracle APEX - 使用列表创建组织结构图
- angular - any 不能分配给类型参数(响应:响应)=> 任何
- java - 当用户输入错误答案三遍时如何终止程序
- c# - dotnet 返回 2 种类型中的 1 种
- java - Java - 无法访问 HashMap 中的 HashMap
- r - R 如何在 PCA 期间修复 DataExplorer 错误:“项目 2 没有长度”