簡體   English   中英

在反應中使用樣式組件時如何在子組件中獲取父道具

[英]How to get parent props in child component when using styled component in react

讓我用一個例子來說明

//NavLink: react router component

const StyledNavLink = styled(NavLink)`
  color: red;
  background: blue;
`
function styledLink(label, to) {
  return <StyledNavLink
    to={to}
    className={(props) => console.log(props)}
  >
    {label}
  </StyledNavLink>
}

這里沒有打印任何內容......如果我使用NavLink而不是StyledNavLink ,我會在控制台中獲得所有道具值。 那么如何在StyledNavLink組件中獲取NavLink屬性呢?

我認為您沒有將道具從父級傳遞到您的樣式化組件中。 它應該有點像這樣 -

const StyledNavLink = styled(NavLink)`
  color: red;
  background: blue;
`;

const Menu = (props) => {
  const { label, to } = props;
  return <StyledNavLink to={to}>{label}</StyledNavLink>;
};

問題

NavLink組件的className屬性與styled-components使用的className屬性沖突。 styled(NavLink)組件只會有一個字符串化的className屬性,而NavLink組件可以采用字符串或 function className值。

解決方案

在不同的道具下傳遞NavLink className道具,並處理樣式化組件中的條件邏輯。

例子:

const StyledNavLink = styled(({ className, navLinkClassName, ...props }) => (
  <NavLink
    {...props}
    className={(props) => {
      let extraClass =
        typeof navLinkClassName === "function"
          ? navLinkClassName(props)
          : navLinkClassName;
      return [className, extraClass].filter(Boolean).join(" ");
    }}
  />
))`
  color: red;
  background: blue;

  &.activeLink {
    color: green;
    background: lightgreen;
  }
`;

用法:

function styledLink(label, to) {
  return (
    <StyledNavLink
      to={to}
      navLinkClassName={(props) => {
        console.log("styledLink", props);
        return props.isActive ? "activeLink" : null;
      }}
    >
      {label}
    </StyledNavLink>
  );
}

...

{styledLink("home", "/")}

如果你想讓styledLink實際上是一個 React 組件:

function StyledLink({ label, to }) {
  return (
    <StyledNavLink
      to={to}
      navLinkClassName={(props) => {
        console.log("StyledLink", props);
        return props.isActive ? "activeLink" : null;
      }}
    >
      {label}
    </StyledNavLink>
  );
}

...

<StyledLink to="/" label="home" />

編輯 how-to-get-parent-props-in-child-component-when-using-styled-component-in-react

在此處輸入圖像描述

暫無
暫無

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

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