样式化组件中的条件呈现

tom*_*son 35 reactjs styled-components

如何在样式组件中使用条件呈现,使用React中的样式组件将我的按钮类设置为活动状态?

在CSS中我会这样做:

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

在样式组件中如果我尝试在类名中使用'&&'它不喜欢它.

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>
     )
  }}
Run Code Online (Sandbox Code Playgroud)

Joã*_*nha 83

你可以这么做

<Tab active={this.state.active} onClick={this.handleButton}></Tab>
Run Code Online (Sandbox Code Playgroud)

你的风格是这样的:

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;
  `}
`;
Run Code Online (Sandbox Code Playgroud)

  • 在 TypeScript 中,您需要使用 `({ active }: any)` 或 [withProps](https://github.com/styled-components/styled-components/issues/630#issuecomment-317277803)。 (5认同)
  • 文档:[基于道具的适应](https://www.styled-components.com/docs/basics#adapting-based-on-props)。 (2认同)
  • 它会在CSS字符串中添加`false`并可能引起麻烦 (2认同)
  • 条件代码不应该用普通的反引号括起来,而应该用 `css\`\`` 括起来 (2认同)

asn*_*007 18

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

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

在上面的例子中,当使用活动prop和limegreen呈现StyledYourComponent时背景将变暗,如果没有提供活动prop或者它是falsy Styled-components会自动为你生成类名:)

如果要添加多个样式属性,则必须使用从样式组件导入的css标记:

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

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;`
  }
`
Run Code Online (Sandbox Code Playgroud)

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

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'
  })
`
Run Code Online (Sandbox Code Playgroud)

  • @CodeFinity 它就在那里:https://styled-components.com/docs/api#css (3认同)

Sal*_*mad 14

这是一个使用 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>
  );
};
Run Code Online (Sandbox Code Playgroud)
<Button isProcessing={this.state.isProcessing} onClick={this.handleClick}>Save</Button>
Run Code Online (Sandbox Code Playgroud)


Vin*_*ang 6

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

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>
    )
  }
}
Run Code Online (Sandbox Code Playgroud)

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

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

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

这是一种非常时髦的造型方式


lau*_*ent 6

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

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

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

        &:active {
            background-color: blue;
        }
    }
`;
Run Code Online (Sandbox Code Playgroud)

所以没有必要关闭/打开刻度来让它工作。