我已经构建了一个 ReactJS 组件库,用于使用 sim 链接通过 NPM 包安装的多个项目。我想使用上下文 API 将数据从组件库提供的父组件传递到我的基础项目,以便由组件库提供的多个使用者组件使用。当我尝试时,我的子组件中的上下文始终未定义。
如果我将我的消费者组件放在我的库中的提供者组件中,它就像一个冠军,但这会破坏我想要实现的目标。如果我将提供者和消费者都导出到我的基础项目,消费者将看不到提供者。
这是来自我的基础项目
import { Screen, COD, GenericSocketServer } from 'component-library'
export default class View extends React.PureComponent {
render() {
return (
<Screen className="screen odmb1">
<GenericSocketServer>
<COD />
</GenericSocketServer>
</Screen>
)
}
}
Run Code Online (Sandbox Code Playgroud)
这是从我的“组件库”导出的提供程序代码
import React from 'react';
import MyContext from "./context";
import COD from './../cod';
export default class GenericSocketServer extends React.Component {
render() {
return (
<MyContext.Provider value={{ foo: 'bar' }}>
<COD />
{this.props.children}
</MyContext.Provider>
);
}
}
Run Code Online (Sandbox Code Playgroud)
这是我在“组件库”中使用的内容代码
import React …Run Code Online (Sandbox Code Playgroud) 我最初关注这个项目是为了将 Firebase 添加到 Gatsby React 应用程序中。它涉及创建 Firebase 上下文,使用提供者包装根布局,然后使用 withFirebase HOC 根据需要使用 Firebase 使用者包装组件。当我最初这样做时,它工作得很好,但我想将代码移动到一个可以在我的应用程序中重用的包中。这是 HOC
export const withFirebase = (Component) => (props) => (
<FirebaseContext.Consumer>
{(firebase) => <Component {...props} firebase={firebase} />}
</FirebaseContext.Consumer>
);
Run Code Online (Sandbox Code Playgroud)
每个页面都以一个呈现以下内容的布局组件开始:
<FirebaseContext.Provider value={this.state.firebase}>
<AppWithAuthentication>
{this.props.children}
</AppWithAuthentication>
</FirebaseContext.Provider>
Run Code Online (Sandbox Code Playgroud)
AppWithAuthentication它本身使用withFirebaseHOC,因为它需要 Firebase 来获取 AuthUser(然后将其存储在上下文中并通过提供者传递),并且它能够很好地做到这一点。
上述所有情况都发生在包代码本身中,但是当我将包导入到其他 React 项目中时,尝试使用 usewithFirebase停止工作,因为用它包装的任何组件都不会收到更新的上下文。我通过检查 React Dev 工具中的组件树来确认这一点,Firebase Provider 获取更新的非空值,内部的使用者AppWithAuthentication也获取它。但我的实际应用程序内的消费者不会更新(并且我在同一库中创建的 AuthUser 上下文也有同样的问题)。
我什至认为,也许父级正在使用更新后的消费者进行渲染,但子级没有重新渲染,但在计算渲染并记录它们之后,很明显,我的应用程序中的组件渲染的次数比AppWithAuthentication. 为了让它更清楚一点,这是我的组件树(从页面根目录的布局组件开始):

这是AppWithAuthentication消费者显示的值:

我完全被困在这里,希望得到任何见解。
编辑:经过更多测试后,我发现了更多信息,但我仍然陷入困境。看起来,当重新加载我的页面时,该Layout组件呈现 …
我想用react-leaflet创建一个自定义组件,该组件显示鼠标的实际位置(x,y),但是我不知道如何创建它。我找到了,react-leaflet-control但似乎不是最新的,当然我读了api文档https://react-leaflet.js.org/docs/en/custom-components.html,但我不明白:/
有人可以给我一个自定义组件的例子吗,一个显示“ Hello world”的组件应该足够了。