reactjs + styled-components with stateful component - 我的样式看不到道具
reactjs + styled-components with stateful component - my styles can't see props
为什么使用class/stateful组件时看不到道具:
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 的例子:
Adapting based on props
您没有将 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>
);
为什么使用class/stateful组件时看不到道具:
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 的例子: Adapting based on props
您没有将 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>
);