首页 > 解决方案 > 对于带有 React Router 的样式化组件,子组件没有 props.theme

问题描述

import {theme} from "./themes";

const App = () => (
  <ThemeProvider theme={theme}>
    <ErrorBoundary showError>
      <Provider store={store}>
        <Router>
          <switch>
            <Route path="/page1" exact component={Page} />
            <Route path="/notfound" component={NotFound} />
          </switch>
        </Router>
      </Provider>
    </ErrorBoundary>
  </ThemeProvider>
export default hot(module)(App);

现在在我的页面组件中,我的道具不包括主题,即 props.theme 未定义

有人可以告诉我哪里出错了吗?

我的页面组件有减速器、位置、匹配道具但没有主题

标签: reactjsreduxreact-routerstyled-components

解决方案


正如文档中所写:

在渲染树中,所有样式组件都可以访问提供的主题

只有他们

这意味着您的“普通”组件不会在其道具中获取主题对象。我花了一些时间才明白。他们本可以在文档中写得更好一些。

Themeprovider 使用react-context api,这意味着您放入其中的所有内容都将在 this.context.yourVaribaleName 下可用,而不是在道具中,这是两个不同的东西。 (有关进一步和正确的用法,请参阅上下文 api 的官方反应文档(上一个链接))

因此,您只需在页面组件中执行以下操作:

const Button = styled.button`
    font-size: 1em;
    color: ${props => props.theme.main};
    border: 2px solid ${props => props.theme.main};
`;

class Page extends React.Component {
    render(){
     return(<Button>Normal</Button>);
    }
}

(styled 组件中的 props.theme 并不意味着您将在其中使用 styled-component 的组件,它的 props 中也有这个)

或者

如果您希望主题对象位于样式组件之外,则在“普通”组件道具中,您必须使用 withTheme HOC。请参阅文档(如前一个答案中所述)


推荐阅读