【发布时间】:2019-12-15 12:51:11
【问题描述】:
我有一个带有全局元素(自定义光标,即鼠标后的圆形 div)的 React 应用程序(使用 CRA 设置),当悬停不同嵌套的其他各种组件时,我想更新/更改其样式,或者不那么深入(在下面提供的结构中,我仅列出一个示例组件)。据我了解,这是 Context API 的一个很好的用例。
我的 App 的结构如下(简化):
<Cursor />
<Layout>
<Content>
<Item />
</Content>
</Layout>
所以当悬停<Item />(在其他组件中)时,我想更新<Cursor /> 组件的样式。
因此,我尝试访问我在 <Cursor /> 组件中设置的函数,位于 <Item /> 组件中。不幸的是,悬停时它不会更新我的状态,因此我的<Cursor /> 的样式不会改变。
我的光标组件看起来像这样(简化):
import React, { Component } from "react"
export const CursorContext = React.createContext(false)
class Cursor extends Component {
constructor(props) {
super(props)
this.state = {
positionX: 0,
positionY: 0,
scrollOffsetY: 0,
display: "none",
isHoveringProjectTeaserImage: false,
}
this.handleMousePosition = this.handleMousePosition.bind(this)
this.handleMouseOverProjectTeaser = this.handleMouseOverProjectTeaser.bind(this)
this.handleMouseLeaveProjectTeaser = this.handleMouseLeaveProjectTeaser.bind(this)
}
handleMousePosition = (mouse) => {
this.setState({
positionX: mouse.pageX,
positionY: mouse.pageY,
display: "block",
scrollOffsetY: window.pageYOffset
})
}
handleMouseOverProjectTeaser = () => {
this.setState({
isHoveringProjectTeaserImage: true
})
}
handleMouseLeaveProjectTeaser = () => {
this.setState({
isHoveringProjectTeaserImage: false
})
}
componentDidMount() {
document.body.addEventListener("mousemove", this.handleMousePosition)
}
componentWillUnmount() {
document.body.removeEventListener("mousemove", this.handleMousePosition)
}
render() {
const {
positionX,
positionY,
display,
scrollOffsetY,
isHoveringProjectTeaserImage
} = this.state
return(
<CursorContext.Provider value={this.state}>
<div>
<StyledCursor
style={ isHoveringProjectTeaserImage
? {backgroundColor: "red", display: `${display}`, top: `${positionY - scrollOffsetY}px`, left: `${positionX}px`}
: {backgroundColor: "yellow", display: `${display}`, top: `${positionY - scrollOffsetY}px`, left: `${positionX}px`}}
/>
</div>
</CursorContext.Provider>
)
}
}
export default Cursor
我的可以悬停的Item Component看起来像这样(简化):
import React, { Component } from "react"
import { CursorContext } from '../Cursor/Index';
class Item extends Component {
constructor(props) {
// not showing stuff in here that's not relevant
}
static contextType = CursorContext
render() {
return(
<CursorContext.Consumer>
{(value) =>
<StyledItem
onMouseOver={value.handleMouseOverProjectTeaser}
onMouseLeave={value.handleMouseLeaveProjectTeaser}
>
</StyledItem>
}
</CursorContext.Consumer>
)
}
}
export default Item
我还需要使用static contextType = CursorContext吗?
当不传递默认值时(我认为它们无论如何都是可选的)我得到一个TypeError: Cannot read property 'handleMouseOverProjectTeaser' of undefined,只要我传递一个很长的false 作为默认值,我的应用程序就会呈现但不会更新我的<Cursor />状态。
我是否正确使用了 Context API?
【问题讨论】:
-
“当不传递默认值时”不确定这是指哪个部分
-
它是指拥有 React.createContext(false) 与拥有 React.createContext()
-
谢谢。赞成详细和集中的问题。
-
我在功能组件malikasinger.medium.com/…找到了这篇关于上下文API的文章
标签: reactjs react-context