为什么在使用类/有状态组件时看不到道具:
const StyledTitle = styled.h1 `
color: ${props => (props.primary ? "royalblue" : "black")};
`;
class Title extends Component {
render() {
return <StyledTitle > {
this.props.children
} < /StyledTitle>;
}
}
const App = () => (
<div>
<Title>Hi, Alice!</Title>
<Title primary>Hi Bob, you are awesome!</Title>
</div>
);
这是Styled-Components&#39;例: Adapting based on props
答案 0 :(得分:3)
您没有将primary
属性传递给样式化组件,因此它可以根据primary
属性呈现逻辑。只需将其添加到组件声明中即可。
const StyledTitle = styled.h1 `
color: ${props => (props.primary ? "royalblue" : "black")};
`;
class Title extends Component {
render() {
return <StyledTitle primary={this.props.primary}> {
this.props.children
} < /StyledTitle>;
}
}
const App = () => (
<div>
<Title>Hi, Alice!</Title>
<Title primary>Hi Bob, you are awesome!</Title>
</div>
);