[英]How to get the return value of parent function to child component in react (Using props)
[英]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" />
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.