gpt4 book ai didi

reactjs - 如何在样式组件之外获取主题?

转载 作者:行者123 更新时间:2023-12-03 13:19:02 24 4
gpt4 key购买 nike

我知道如何从使用 styled 方式创建的组件中获取主题:

const StyledView = styled.View`
color: ${({ theme }) => theme.color};
`;

但是如何从普通组件获取或将其应用于不同属性?示例:

index.js

<ThemeProvider theme={{ color: 'red' }}>
<Main />
</ThemeProvider>

main.js

<View>
<Card aCustomColorProperty={GET COLOR FROM THEME HERE} />
</View>

Notice how the property that needs the theme is not called style

最佳答案

从 v5.0 开始,您可以使用 useTheme 钩子(Hook):

import React, { useTheme } from 'styled-components';

export function MyComponent() {
const theme = useTheme();

return <p style={{ color: theme.color }}>Text</p>;
}

您还可以使用withTheme自 v1.2 以来我很久以前就贡献了高阶组件:

import { withTheme } from 'styled-components'

class MyComponent extends React.Component {
render() {
const { theme } = this.props

console.log('Current theme: ', theme);
// ...
}
}

export default withTheme(MyComponent)
<小时/><小时/><小时/>

original response below (ignore this!)

虽然没有官方解决方案,但我现在已经想到了:

创建一个高阶组件,负责获取当前主题并将其作为 Prop 传递给组件:

import React from 'react';
import { CHANNEL } from 'styled-components/lib/models/ThemeProvider';

export default Component => class extends React.Component {
static contextTypes = {
[CHANNEL]: React.PropTypes.func,
};

state = {
theme: undefined,
};

componentWillMount() {
const subscribe = this.context[CHANNEL];
this.unsubscribe = subscribe(theme => {
this.setState({ theme })
});
}

componentWillUnmount() {
if (typeof this.unsubscribe === 'function') this.unsubscribe();
}

render() {
const { theme } = this.state;

return <Component theme={theme} {...this.props} />
}
}

然后,在您需要访问主题的组件上调用它:

import Themable from './Themable.js'

const Component = ({ theme }) => <Card color={theme.color} />

export default Themable(Component);

关于reactjs - 如何在样式组件之外获取主题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40796973/

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