use*_*776 1 reactjs styled-components
如何根据呈现它的 React 组件的状态让样式化组件呈现不同的 css 规则?
以下不起作用:
class Container extends React.Component<ContainerProps, ContainerState> {
constructor(props: ContainerProps) {
super(props);
this.state = {
highlight: true,
dark: false
};
}
OuterWrapper = styled.div`
display: inline-block;
padding: 20px;
${this.state.dark && `
background-color: 'gray';
`};
`;
return (
<this.OuterWrapper>
...
</this.OuterWrapper>
);
}
Run Code Online (Sandbox Code Playgroud)
类型错误:无法在新容器中读取未定义的属性“dark”
实现这一目标的最佳方法是将 prop 传递给您从中获得的元素styled-comopnent。
// outside of the component
interface OuterWrapperProps {
dark: boolean;
}
const OuterWrapper = styled.div<OuterWrapperProps>`
display: inline-block;
padding: 20px;
${props => props.dark && css`
background-color: 'gray';
`};
`;
Run Code Online (Sandbox Code Playgroud)
当你渲染那个元素时:
...
<OuterWrapper dark={this.state.dark}> ... </OuterWrapper>
...
Run Code Online (Sandbox Code Playgroud)
而且您仍然可以从您的state!
这样做有助于提高代码的可读性,并遵循文档的建议。
| 归档时间: |
|
| 查看次数: |
4070 次 |
| 最近记录: |