如何区分样式化组件是使用 React 组件还是使用其他样式化组件/原生标签创建的
How to distinguish if styled component was created with React component or with another styled component / native tag
我有一个非常复杂的组件,我想阻止在那里传递 React 组件和使用 React 组件创建的样式化组件。我想要允许的唯一组件是 1) 其他 "simple" 样式组件 2) 本机标签(如 div)。
例如:
function SophisticatedComponent({
element,
}) {
if (isReactComponent(element)) {
throw new Error('React components are forbidden!');
}
...
}
function ReactComponent() {
return (
<div/>;
);
}
<SophisticatedComponent element={<ReactComponent/>}/> // THROW
<SophisticatedComponent element={<div><ReactComponent/></div>}/> // OK
const StyledComponent = styled.div``;
<SophisticatedComponent element={<StyledComponent><ReactComponent/></StyledComponent>}/> // OK
const StyledReactComponent = styled(ReactComponent)``;
<SophisticatedComponent element={<StyledReactComponent/>}/> // THROW
如何编写这个 isReactComponent
函数来区分 React 组件和样式化组件?
这是函数:
function isReactComponent({type}) {
if (typeof type === 'string') { // <div><ReactComponent/></div>
return false;
}
if (typeof type === 'object') { // <ReactComponent/>
return true;
}
if (typeof type === 'function' && typeof type.target === 'string') { // <StyledComponent><ReactComponent/></StyledComponent>
return false;
}
if (typeof type === 'function' && typeof type.target === 'object') { // <StyledReactComponent/>
return true;
}
}
我有一个非常复杂的组件,我想阻止在那里传递 React 组件和使用 React 组件创建的样式化组件。我想要允许的唯一组件是 1) 其他 "simple" 样式组件 2) 本机标签(如 div)。 例如:
function SophisticatedComponent({
element,
}) {
if (isReactComponent(element)) {
throw new Error('React components are forbidden!');
}
...
}
function ReactComponent() {
return (
<div/>;
);
}
<SophisticatedComponent element={<ReactComponent/>}/> // THROW
<SophisticatedComponent element={<div><ReactComponent/></div>}/> // OK
const StyledComponent = styled.div``;
<SophisticatedComponent element={<StyledComponent><ReactComponent/></StyledComponent>}/> // OK
const StyledReactComponent = styled(ReactComponent)``;
<SophisticatedComponent element={<StyledReactComponent/>}/> // THROW
如何编写这个 isReactComponent
函数来区分 React 组件和样式化组件?
这是函数:
function isReactComponent({type}) {
if (typeof type === 'string') { // <div><ReactComponent/></div>
return false;
}
if (typeof type === 'object') { // <ReactComponent/>
return true;
}
if (typeof type === 'function' && typeof type.target === 'string') { // <StyledComponent><ReactComponent/></StyledComponent>
return false;
}
if (typeof type === 'function' && typeof type.target === 'object') { // <StyledReactComponent/>
return true;
}
}