样式组件中的条件渲染

conditional rendering in styled components

我如何在样式化组件中使用条件渲染来设置我的按钮 class 在 React 中使用样式化组件激活?

在 css 中,我会这样做:

<button className={this.state.active && 'active'}
      onClick={ () => this.setState({active: !this.state.active}) }>Click me</button>

在样式组件中,如果我尝试在 classname 中使用“&&”,它不喜欢它。

import React from 'react'
import styled from 'styled-components'

const Tab = styled.button`
  width: 100%;
  outline: 0;
  border: 0;
  height: 100%;
  justify-content: center;
  align-items: center;
  line-height: 0.2;
`

export default class Hello extends React.Component {
  constructor() {
    super()
    this.state = {
      active: false
    }  
    this.handleButton = this.handleButton.bind(this)
}

  handleButton() {
    this.setState({ active: true })
  }

  render() {
     return(
       <div>
         <Tab onClick={this.handleButton}></Tab>
       </div>
     )
  }}

你可以简单地这样做

<Tab active={this.state.active} onClick={this.handleButton}></Tab>

在你的风格中是这样的:

const Tab = styled.button`
  width: 100%;
  outline: 0;
  border: 0;
  height: 100%;
  justify-content: center;
  align-items: center;
  line-height: 0.2;

  ${({ active }) => active && `
    background: blue;
  `}
`;

我没有注意到您的示例中有任何 &&,但是对于样式化组件中的条件渲染,您可以执行以下操作:

// Props are component props that are passed using <StyledYourComponent prop1="A" prop2="B"> etc
const StyledYourComponent = styled(YourComponent)`
  background: ${props => props.active ? 'darkred' : 'limegreen'}
`

在上面的例子中,当 StyledYourComponent 使用 active prop 渲染时,背景将是暗红色,如果没有提供 active prop 或者它是 falsy,背景将是暗绿色 Styled-components 自动为你生成类名:)

如果你想添加多个样式属性,你必须使用 css 标签,它是从 styled-components 导入的:

我没有注意到您的示例中有任何 &&,但是对于样式化组件中的条件渲染,您可以执行以下操作:

import styled, { css } from 'styled-components'
// Props are component props that are passed using <StyledYourComponent prop1="A" prop2="B"> etc
const StyledYourComponent = styled(YourComponent)`
  ${props => props.active && css`
     background: darkred; 
     border: 1px solid limegreen;`
  }
`

或者您也可以使用对象来传递样式,但请记住 CSS 属性应该是驼峰式:

import styled from 'styled-components'
// Props are component props that are passed using <StyledYourComponent prop1="A" prop2="B"> etc
const StyledYourComponent = styled(YourComponent)`
  ${props => props.active && ({
     background: 'darkred',
     border: '1px solid limegreen',
     borderRadius: '25px'
  })
`

如果您的状态在 class 组件中定义如下:

class Card extends Component {
  state = {
    toggled: false
  };
  render(){
    return(
      <CardStyles toggled={this.state.toggled}>
        <small>I'm black text</small>
        <p>I will be rendered green</p>
      </CardStyles>
    )
  }
}

使用基于该状态的三元运算符定义样式组件

const CardStyles = styled.div`
  p {
    color: ${props => (props.toggled ? "red" : "green")};
  }
`

它应该只将此处的 <p> 标记呈现为绿色。

这是一种非常sass的造型方式

这是一个使用 TypeScript 的简单示例:

import * as React from 'react';
import { FunctionComponent } from 'react';
import styled, { css } from 'styled-components';

interface IProps {
  isProcessing?: boolean;
  isDisabled?: boolean;
  onClick?: () => void;
}

const StyledButton = styled.button<IProps>`
  width: 10rem;
  height: 4rem;
  cursor: pointer;
  color: rgb(255, 255, 255);
  background-color: rgb(0, 0, 0);

  &:hover {
    background-color: rgba(0, 0, 0, 0.75);
  }

  ${({ disabled }) =>
    disabled &&
    css`
      opacity: 0.5;
      cursor: not-allowed;
    `}

  ${({ isProcessing }) =>
    isProcessing &&
    css`
      opacity: 0.5;
      cursor: progress;
    `}
`;

export const Button: FunctionComponent<IProps> = ({
  children,
  onClick,
  isProcessing,
}) => {
  return (
    <StyledButton
      type="button"
      onClick={onClick}
      disabled={isDisabled}
      isProcessing={isProcessing}
    >
      {!isProcessing ? children : <Spinner />}
    </StyledButton>
  );
};
<Button isProcessing={this.state.isProcessing} onClick={this.handleClick}>Save</Button>

我没见过这种语法,我觉得当你需要使一个完整的块有条件时,它是最干净的:

const StyledButton = styled(button)`
    display: flex;
    background-color: white;

    ${props => !props.disabled} {
        &:hover {
            background-color: red;
        }

        &:active {
            background-color: blue;
        }
    }
`;

所以不需要 close/open 滴答让它工作。

似乎也可以通过有条件地应用类名来使用它们:

const BoxClassname = styled.div.attrs((props) => ({
  className: clsx(props.$primary && "primary")
}))`
  background: #000;
  height: 1px;
  width: 50px;
  &.primary {
    background: pink;
  }
`;

/*
// You could also use a second component instead of .attrs
export const BoxClassname = (props) => {
  return (
    <BoxClassnameWrapper
      className={clsx(props.$primary && "primary")}
      {...props}
    />
  );
};
*/

我喜欢这种语法的地方是你不要将 JS 和 CSS 混用太多。

限制是它看起来更慢,请参阅 this demo code sandbox 进行性能比较。我真的不明白为什么:/因为逻辑上。

看完Josh Comeau take on using CSS variables in Styled Components我就有了这个想法。

  • CSS 变量让你配置...变量(切换颜色等)
  • 从逻辑上讲,classNames + CSS 选择器让您定义条件

毕竟,这个逻辑已经存在于CSS中,className 已经用于处理条件渲染。 Styled Components 有助于保持样式的清晰隔离并处理高级场景,但我不喜欢它过多地干预样式。