如何获得样式化的组件,以根据呈现它的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> ); }
TypeError:无法在新容器中读取未定义的属性“ dark”
实现此目标的最佳方法是将prop传递给您从中获得的元素styled-comopnent。
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'; `}; `;
当您渲染该元素时:
... <OuterWrapper dark={this.state.dark}> ... </OuterWrapper> ...
而且,您仍然可以控制主题state!
state
这样做有助于提高代码的可读性,并遵循文档的建议。