样式组件中的条件渲染 [英] conditional rendering in styled components

查看:37
本文介绍了样式组件中的条件渲染的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在样式化组件中使用条件渲染来使用 React 中的样式化组件将我的按钮类设置为活动状态?

在 css 中,我会这样做:

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

从 'react' 导入 React从样式组件"导入样式const Tab = styled.button`宽度:100%;大纲:0;边框:0;高度:100%;对齐内容:居中;对齐项目:居中;行高:0.2;`导出默认类 Hello 扩展 React.Component {构造函数(){极好的()this.state = {活动:假}this.handleButton = this.handleButton.bind(this)}手柄按钮(){this.setState({ active: true })}使成为() {返回(<div><Tab onClick={this.handleButton}></Tab>

)}}

解决方案

你可以这样做

在你的风格中是这样的:

const Tab = styled.button`宽度:100%;大纲:0;边框:0;高度:100%;对齐内容:居中;对齐项目:居中;行高:0.2;${({active }) =>主动&&`背景:蓝色;`}`;

How can I use conditional rendering in styled-components to set my button class to active using styled-components in React?

In css I would do it similarly to this:

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

In styled components if I try to use '&&' in the classname it doesn't like it.

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>
     )
  }}

解决方案

You can simply do this

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

And in your styles something like this:

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

这篇关于样式组件中的条件渲染的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆