样式化组件中的条件呈现

问题描述 投票:21回答:3

如何在样式组件中使用条件呈现,使用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>
     )
  }}
reactjs styled-components
3个回答
61
投票

你可以这么做

<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;
  `}
`;

11
投票

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

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

在上面的例子中,当使用活动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;`
  }
`

或者您也可以使用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'
  })
`

1
投票

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

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>标签为绿色。

这是一种非常流行的造型方式

© www.soinside.com 2019 - 2024. All rights reserved.