小编典典

样式化组件中的条件渲染

reactjs

如何在样式组件中使用条件渲染以使用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>
     )
  }}

阅读 277

收藏
2020-07-22

共1个答案

小编典典

你可以简单地做到这一点

<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;
  `}
`;
2020-07-22