问题描述
基本上我希望能够定义一个组件列表,这些组件可以紧挨着组件层次结构中的子组件。 有没有一种程序化的方法来检查这个?
该列表基本上是一个类的数组
const allowed_parents = [Parent1, Parent2, Parent3];
然后
<UnListedParent>
.
.
.
<Child />
</UnListedParent>
应该抛出错误
1楼
您无法直接从具有任何已知公共React API的子项访问父项。
当然有“hacky”方式,例如,对父进行createRef
并将其传递给子React.Children.map
,使用React.Children.map
和React.cloneElement
编程方式进行,但这是一个糟糕的设计,我不会去甚至在这里发布,与该代码无关:D
我认为更好的方法是更好地与React
哲学和单向自上而下流程保持一致,使用HigherOrderComponent包装的“允许父母”的组合,将特定标志传递给他们“允许”的孩子,然后检入如果标志存在则为子,否则为错误。
这可能大概是
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
);