我想创建 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/