基本上,我希望能够定义一个组件列表,这些组件可以位于组件层次结构中子组件的正上方。有没有一种编程方式来检查这一点?
该列表基本上是一个类数组,例如
const allowed_parents = [Parent1, Parent2, Parent3];
and then
<UnListedParent>
.
.
.
<Child />
</UnListedParent>
应该抛出一个错误
您无法使用任何已知的公共 React API 直接从子级访问父级。
当然有一些“hacky”方法,比如createRef
在父母身上并将其传递给孩子,使用React.Children.map
, and React.cloneElement
以编程方式,但这是一个非常糟糕的设计,我什至不会将其发布在这里,以免与该代码相关联:D
不过,我认为更好的方法可以更好地与React
哲学和单向自上而下的流程是使用HigherOrderComponent包装的“允许的父母”的组合,将特定的标志传递给他们“允许”的孩子,然后检查孩子是否存在标志,否则会出错。
这可能大约是这样的this https://codesandbox.io/s/w78042y66k
import React, { useState } from "react";
import ReactDOM from "react-dom";
const Child = ({ isAllowed }) => {
if (!isAllowed) {
throw new Error("We are not allowed!");
}
return <div>An allowed child.</div>;
};
const allowParentHOC = Wrapper => {
return ({ children, ...props }) => {
return (
<Wrapper {...props}>
{React.Children.map(children, child =>
React.cloneElement(child, {
isAllowed: true
})
)}
</Wrapper>
);
};
};
const Parent1 = allowParentHOC(props => <div {...props} />);
const Parent2 = allowParentHOC(props => <div {...props} />);
const UnListedParent = ({ children }) => children;
class ErrorBoundary extends React.Component {
state = { hasError: false };
componentDidCatch(error, info) {
this.setState({ hasError: true, info });
}
render() {
if (this.state.hasError) {
// You can render any custom fallback UI
return (
<>
<h1>This Child was not well put :(</h1>
<pre>{JSON.stringify(this.state.info, null, 2)}</pre>
</>
);
}
return this.props.children;
}
}
class App extends React.Component {
state = {
isUnAllowedParentShown: false
};
handleToggle = () =>
this.setState(({ isUnAllowedParentShown }) => ({
isUnAllowedParentShown: !isUnAllowedParentShown
}));
render() {
return (
<>
<button onClick={this.handleToggle}>Toggle Versions</button>
{this.state.isUnAllowedParentShown ? (
<UnListedParent>
<Child />
</UnListedParent>
) : (
<>
<Parent1>
<Child />
</Parent1>
<Parent2>
<Child />
</Parent2>
</>
)}
</>
);
}
}
export default App;
const rootElement = document.getElementById("root");
ReactDOM.render(
<ErrorBoundary>
<App />
</ErrorBoundary>,
rootElement
);
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)