样式化组件中的条件渲染

新手上路,请多包涵

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

原文由 tom harrison 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 793
2 个回答

你可以简单地做到这一点

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

原文由 João Cunha 发布,翻译遵循 CC BY-SA 3.0 许可协议

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

 // 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'
  })
`

原文由 asn007 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进