javascript - 是否可以在 react 中强制一个组件在另一个组件内使用?

标签 javascript reactjs

我想创建 2 个 React 组件 <Father /><Child />并强制开发者使用Child仅在内部 Father :

<Father>
    <!-- should be fine -->
    <Child />
</Father>

<!-- should throw an error -->
<Child />

有什么办法吗?如果是这样,我应该使用什么语法?

最佳答案

您可以利用context API来确定子项在父项中是否有父亲

您可以做到这一点的方法是让您的父亲组件呈现 ContextProvider 并且您的 child 使用上下文

const FatherContext = React.createContext(null); // default value used if father not in hierarchy

const Father = ({children}) => {
   // Component Logic here
   return (
       <FatherContext.Provider value={"Father"}>
        {/* rest content */
        {children}
       </FatherContext.Provider>
   )
}

你的 child 可能会像

const Child = () => {
   const context = useContext(FatherContext);
   if(context == null) {
       console.warn("Child must be rendered inside of Father component"); // You can throw an error here too
   }

   return (...)
}

现在,根据您使用的 React 版本,Context 的实现有所不同,但思想保持不变

关于javascript - 是否可以在 react 中强制一个组件在另一个组件内使用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61780841/

相关文章:

javascript - 如何将焦点移出 IFrame

javascript - 如何在 Three.js 中正确实现 Cook-Torrance 着色?

javascript - 如何在iOS webview中控制iOS状态栏背景颜色

javascript - 在外部单击时隐藏多个元素的最有效方法?

javascript - 如何像在 9gag.com 上那样显示部分图像

javascript - DIV 标签和 HTML5 元素(章节、文章)之间应该使用什么和有什么不同?

reactjs - 如何修复自定义 Hook 中的 "useEffect has a missing dependency"

javascript - 修改 localStorage 时,mapStateToProps 不更新 props

asynchronous - 如何在webpack中加载远程文件

coffeescript - 在 React 中链接两个输入字段