gpt4 book ai didi

javascript - 如何扩展或合并 Styled Components 主题

转载 作者:行者123 更新时间:2023-11-28 14:40:14 28 4
gpt4 key购买 nike

我有一个基于 Styled Components 的组件库,它有自己的一组主题设置,在大多数情况下永远不需要覆盖。我正在将这个组件库拉到另一个元素中,该元素也使用 Style Components 并有自己的主题。我如何从组件库和这个元素中导入组件,并确保它们中的每一个都只提供来自其相应 repo 的主题值?我不想覆盖我的组件库主题,我想管理 2 个单独的主题,以便我的组件库可以访问默认主题,而这个其他元素可以为其自己的组件定义一个单独的主题对象

例子:独立元素

const theme = {
colors: {
error: '#f23f3f',
}
}

import { SeparateProjectThemeProvider } from 'separate-proj';

class App extends React.Component {
render () {
return (
<SeparateProjectThemeProvider theme={theme}>
<h1>Hello</h1>
</SeparateProjectThemeProvider>
)
}
}

组件库

const theme = {
colors: {
brand: '#3bbdca',
}
}

import { ThemeProvider } from "styled-components";

import defaultTheme from "./theme-settings";

const mergeThemes = (theme1, theme2) => {
const mergedTheme = { ...theme1, ...theme2 };
return mergedTheme;
};

const CustomThemeProvider = props => {
const customTheme = {
custom: Object.assign({}, defaultTheme)
};

return (
<ThemeProvider theme={mergeThemes(customTheme, props.theme)}>
{props.children}
</ThemeProvider>
);
};

export default CustomThemeProvider;

最佳答案

下面的代码将演示几个选项——使用适当的主题提供程序 (WrappedTitle) 预先包装每个组件库组件,或者在您使用它们时包装它们(“Hello Component World!”部分)。

// Sample component-lib/index.js
import React from 'react';
import styled from "styled-components";
import {ThemeProvider} from "styled-components";

const theme = {
titleColor: "green"
};
export const CompLibThemeProvider = props => {
const customTheme = Object.assign({}, theme, props.theme);
return (
<ThemeProvider theme={customTheme}>
{props.children}
</ThemeProvider>
);
};

export const Title = styled.h1`
font-size: 1.5em;
text-align: center;
color: ${props => props.theme.titleColor};
`;
export const WrappedTitle = (props) => {
return (<CompLibThemeProvider><Title {...props}/></CompLibThemeProvider>);
};

下面是一些示例元素代码:

// App.js
import React from 'react';
import styled from 'styled-components';
import {Title, CompLibThemeProvider, WrappedTitle} from 'component-lib';
import {ThemeProvider} from "styled-components";

const theme = {
titleColor: "red"
};

export const BigTitle = styled.h1`
font-size: 5em;
text-align: center;
color: ${props => props.theme.titleColor};
`;

const ProjectThemeProvider = props => {

return (
<ThemeProvider theme={Object.assign({}, theme, props.theme)}>
{props.children}
</ThemeProvider>
);
};
const App = () => {
return (
<>
<ProjectThemeProvider>
<>
<BigTitle>Hello Big World!</BigTitle>
<WrappedTitle>Hello Pre-wrapped World!</WrappedTitle>
</>
</ProjectThemeProvider>
<CompLibThemeProvider><Title>Hello Component World!</Title></CompLibThemeProvider>
</>
);
}

export default App;

关于javascript - 如何扩展或合并 Styled Components 主题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53054861/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com