簡體   English   中英

無論多深,我如何將 Parent 樣式組件中的 prop 傳遞給其子樣式組件

[英]How do I pass a prop from a Parent styled component to its children's styled components no matter how deep

我有這些樣式的組件:

import styled, { css } from 'styled-components'

const Container = styled.div`
  background-color: ${props => props.theme === "light" ? "hsl(0, 0%, 98%)" : "hsl(235, 24%, 19%)" };
  border-radius: 4px;
  box-shadow: ${props => props.theme === "light" ? "0px 35px 50px -15px rgba(194, 195, 214, 0.5)" : "0px 35px 50px -15px rgba(0, 0, 0, 0.5)" };
`

const Footer = styled.footer`
  padding: 25px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  color: ${props => props.theme === "light" ? "hsl(236, 9%, 61%)" : "hsl(234, 11%, 52%)" };
  font-size: 14px;
`

const Nav = styled.nav`
  display: flex;
  align-items: center;
  justify-content: space-between;
  color: inherit;
`

const NavItem = styled.a`
  cursor: pointer;
  display: inline-block;
  color: inherit;

  &:hover {
    color: ${props => props.theme === "light" ? "hsl(235, 19%, 35%)" : "hsl(236, 33%, 92%)" };
  }

  &:not(:last-of-type) {
    margin-right: 15px;
  }

  ${({ active }) =>
    active &&
    css`
      color: hsl(220, 98%, 61%);
    `
  }
`

const ClearList = styled.p`
  color: inherit;
  cursor: pointer;

  &:hover {
    color: ${props => props.theme === "light" ? "hsl(235, 19%, 35%)" : "hsl(234, 39%, 85%)" };
  }
`

我有一個名為TodoList組件, TodoList帶有一個theme道具,可以像這樣傳遞給樣式組件:

const TodoList = ({ theme }) => {
  return (
    <Container theme={theme}>
      <Footer theme={theme}>
        <p>5 items left</p>
        <Nav>
          <NavItem theme={theme}>All</NavItem>
          <NavItem theme={theme}>Active</NavItem>
          <NavItem theme={theme}>Completed</NavItem>
        </Nav>
        <ClearList theme={theme}>Clear Completed</ClearList>
      </Footer>
    </Container>
  )
}

export default TodoList

我如何在Container元素中只調用一次theme道具,並使所有子元素(如 Clearlist、NavItems 和 Footer)都可以訪問它而不顯式傳遞它們

謝謝

您可以使用 ThemeProvider 解決此問題

訪問此鏈接https://styled-components.com/docs/advanced

例子

// Define our button, but with the use of props.theme this time
const Button = styled.button`
  color: ${props => props.theme.fg};
  border: 2px solid ${props => props.theme.fg};
  background: ${props => props.theme.bg};

  font-size: 1em;
  margin: 1em;
  padding: 0.25em 1em;
  border-radius: 3px;
`;

// Define our `fg` and `bg` on the theme
const theme = {
  fg: "palevioletred",
  bg: "white"
};

// This theme swaps `fg` and `bg`
const invertTheme = ({ fg, bg }) => ({
  fg: bg,
  bg: fg
});

render(
  <ThemeProvider theme={theme}>
    <div>
      <Button>Default Theme</Button>

      <ThemeProvider theme={invertTheme}>
        <Button>Inverted Theme</Button>
      </ThemeProvider>
    </div>
  </ThemeProvider>
);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM