【发布时间】:2020-11-23 20:34:28
【问题描述】:
我使用带有 MDX 插件的 Gatsby。所以我可以在 Markdown 中使用 React 组件。没关系。
我有组件,可以互相交谈。为此,我使用Lifting State Up Pattern。没关系。
这是一个基本的 Counter 示例,用于展示我的概念验证代码。
import React from "react"
export class Counter extends React.Component {
constructor(props) {
super(props)
this.state = { count: 0 }
this.handleCounterUpdate = this.handleCounterUpdate.bind(this)
}
handleCounterUpdate() {
this.setState({ count: this.state.count + 1 })
}
render() {
const children = React.Children.map(this.props.children, child => {
const additionalProps = {}
additionalProps.count = this.state.count
additionalProps.handleCounterUpdate = this.handleCounterUpdate
return React.cloneElement(child, additionalProps)
})
return <div>{children}</div>
}
}
export function Display({ count }) {
return <h2>Current counter is: {count}</h2>
}
export function UpdateButton({ handleCounterUpdate }) {
return <button onClick={handleCounterUpdate}>Increment couter by one</button>
}
通过此设置,您可以使用这样的组件
<Counter>
<Display />
<UpdateButton />
</Counter>
甚至像这样
<Counter>
<Display />
<UpdateButton />
<Display />
<Display />
</Counter>
没关系。
在现实世界中,封闭的 Counter 组件(状态持有者)将类似于 Layout 组件。 <Layout> 在模板中使用并呈现 MDX 页面。看起来像这样:
<SiteLayout>
<SEO title={title} description={description} />
<TopNavigation />
<Display /> // The state holder is <SiteLayout>, not <Counter>
<Breadcrumb location={location} />
<MDXRenderer>{page.body}</MDXRenderer> // The rendered MDX
</SiteLayout>
<UpdateButton>(在现实世界中类似于 <AddToCartButton>)位于 MDX 页面上,不再是 <Layout> 组件的直接子代。
这种模式不再起作用了。
我该如何解决这个问题?
谢谢大家
【问题讨论】:
-
您应该能够将道具从您的
<MDXRenderer />传递到<AddToCartButton> -
我认为您可以设置上下文提供程序并在间接子组件中使用其状态
-
谢谢@Mark 你支持扩展和覆盖
MDXRenderer吗?我还在学习 React。 -
Stefan,我实际上会推荐 Derek 的提议。它会给你一个很好的上下文 API 课程。
-
是的@Mark。我也意识到了这一点。阅读并制作了 POC。一切都很好。将其发布为像我这样的其他初学者的解决方案。如果您喜欢,请提出改进意见和建议。谢谢大家的帮助。
标签: javascript reactjs react-state