简体   繁体   中英

Child Components have no props.theme for Styled Components with React Router

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);

Now in my Page Component my props do not include theme ie props.theme is undefined

Can someone tell me where I am going wrong?

My Page component has the reducer,location,match props but no theme

To consume the theme at the component level and not inside styling, you need to use the withTheme higher order component. https://www.styled-components.com/docs/api#withtheme

As written in the docs :

In the render tree all styled-components will have access to the provided theme

and only them!

This means that your 'normal' components won't get the theme-object in their props. It took me sometime to get that. They could have written it a bit better in the docs.

The Themeprovider uses the react-context api , which means everything you put in there will be avaiable under this.context.yourVaribaleName and not in the props these are two different things. (for further and right usage see the offical react doc for the context api (previous link))

So in the Page Component just you do:

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>);
    }
}

(the props.theme in the styled component does not mean that the components that you will use the styled-component in, also has this in its props)

OR

If you want your theme object outside of a styled component, in a 'normal' components props you have to use the withTheme HOC. See docs . (as mentioned in a former answer )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM