我在我的应用程序中使用样式组件在CodeSandbox中。请参考以下网址 https://lrn6vmq297.sse.codesandbox.io/
每当我进行一些更改时,控制台都会说。
Warning: PropclassNamedid not match.
Warning: Prop
did not match.
It looks like you've wrapped styled() around your React component (Component), but the className prop is not being passed down to a child. No styles will be rendered unless className is composed within your React component.
而且UI无法按预期呈现。有人知道我为什么遇到这个问题吗?请查看上面的网址。
谢谢
基本上,您需要通过this.props.className或生成props.className的解构className,styled- components然后将其手动应用于要设置样式的组件。否则,您不会将className应用于任何内容,因此不会看到任何样式更改。
this.props.className
props.className
className
styled- components
工作示例:
components / LinkComponent.js (functional component接受由className创建styled()并props传递给下面创建的样式化组件的,您需要将它们手动应用于该Link组件)
functional component
styled()
props
Link
import React from "react"; import PropTypes from "prop-types"; import { Link } from "react-router-dom"; const LinkComponent = ({ className, children, link }) => ( <Link className={className} to={link}> {children} </Link> ); LinkComponent.propTypes = { className: PropTypes.string.isRequired, link: PropTypes.string.isRequired, children: PropTypes.string.isRequired }; export default LinkComponent;
components / StyledLink.js (导入functional component以上内容并将其传递给styled()您-您还可以创建样式化主题以更新styled()元素)
import styled from "styled-components"; import LinkComponent from "./LinkComponent"; const StyledLink = styled(LinkComponent)` color: ${props => (!props.primary && !props.danger ? "#03a9f3" : "#ffffff")}; background-color: ${props => { if (props.primary) return "#03a9f3"; if (props.danger) return "#f56342"; return "transparent"; }}; font-weight: bold; margin-right: 20px; padding: 8px 16px; transition: all 0.2s ease-in-out; border-radius: 4px; border: 2px solid ${props => { if (props.primary) return "#03a9f3"; if (props.danger) return "#f56342"; return "#03a9f3"; }}; &:hover { color: ${props => (!props.primary && !props.danger ? "#0f7ae5" : "#ffffff")}; background-color: ${props => { if (props.primary) return "#0f7ae5"; if (props.danger) return "#be391c"; return "transparent"; }}; text-decoration: none; border: 2px solid ${props => (props.danger ? "#be391c" : "#0f7ae5")}}; } `; export default StyledLink;
components / Header.js (导入StyledLink上面创建的样式化组件并加以利用- 传递给该组件的所有其他道具都将自动传递给function,但是在这种情况下,您需要解构该组件prop才能利用它)
StyledLink
function
prop
import React from "react"; import StyledLink from "./StyledLink"; export default () => ( <nav className="container"> <StyledLink primary link="/">Home</StyledLink> <StyledLink danger link="/about">About</StyledLink> <StyledLink link="/portfolio">Portfolio</StyledLink> </nav> );