是否可以使用样式化组件为道具设置中间件



我在玩有样式的组件,遇到了一个问题。我想创建一个道具,对我传递给的任何样式的组件都做同样的事情。

例如:

<StyledDiv bg="blue"/>

在传递给它的任何样式组件中,这个道具都应该被解释为background-color: blue,而无需手动执行以下操作:

const StyledDiv = styled.div`
${({bg}) => `background-color: ${bg}`}
`

对于每一个组件。这可能吗?

我想出了一个解决方案,但在我看来并不好。我找不到任何一种带有样式组件的中间件解决方案,所以我只制作了一个包装器函数,将样式组件作为参数。

包装器函数返回一个新组件,该组件在将道具传递给样式组件之前对道具进行修改。以下是实现:

import styled from 'styled-components';
const _globalProps = {
sm: props => `
@media screen and (max-width: 700px) {
${props}
}
`,
}
const _styleWrapper = (StyledComponent) => {
return (props) => {
// bypass immutable react props object
props = {...props};
// access styled component style body
const styleRules = StyledComponent.componentStyle.rules;
// if the prop you passed is in _globalProps, add the global style to the style body
for (const prop in props) {
const gProp = _globalProps[prop];
if (gProp) styleRules[styleRules.length] = gProp(props[prop]);
}
// return the styled component with the modified style body
return (
<StyledComponent {...props}>
{props.children}
</StyledComponent>
);
};
};
const Container = _styleWrapper(styled.div`
background-color: ${props => props.backgroundColor};
`);
export default Container;

现在,对于任何封装在_styleWrapper中的样式组件,都可以传递一个名为sm的道具,该道具将向该组件添加一个具有指定字段的媒体查询。

示例:

import Container from './components/styled/Container';
function App() {
return (
<Container sm="margin: 0" backgroundColor="red">
...
</Container>
);
}

当屏幕宽度下降到700px以下时,容器现在将失去其余量。

最新更新